Rails respond_with nothing?
I have a create action in one of my controllers which responds to ajax and html requests. Inside the create action I set an instance variable (@location) using a find_or_initialize_by_such_and_such. I then test to see if the location already exists or not using this:
if @location.id.nil?
@location.save
respond_with(@location, :location => root_path) do |format|
format.html { redirect_to root_path }
end
end
This works fine since basically the partial (create.js.erb) appends the newly saved location object to a list.
The problem occurs when the user inputs a location which already exists (i.e. has an id). In such a case I do not want the found location to be appended to the list, as it would cause duplication (all the locations are already there). Since @location.id.nil?
is false in that scenario the code within the above block is obviously not executed, but I am having a hard time figuring out how to handle that situation. I tried doing something like:
respond_with(nil, :location => root_path) do |format|
format.ht开发者_JS百科ml { redirect_to root_path }
end
but the js.erb file still grabs the @location instance variable and executes the javascript that adds the object to the list.
What would be the best way to therefore to work around this, so that in cases where the find_or_initialize_by returns an already created object, the response will not execute the javascript to append this object to a list?
remove
respond_with(nil, :location => root_path) do |format|
format.html { redirect_to root_path }
end
and leave only this
redirect_to root_path
if you don't any extra respond
精彩评论