问题
When using location in respond with, it is ignoring validation errors and redirecting to the specified location. Is this expected behavior?
I checked in the responder module that it checking if there are any errors on the model. I inspected the model and it contains validation errors in the @solution object. What am I missing here?
controller:
def create
@problem = Problem.find(params[:problem_id])
@solution = @problem.solutions.build params[:solution]
@solution.save
respond_with(@solution, :location => detail_problem_solution_path(@problem, @solution)
end
model:
validates :body, :presence => true, :unless => :reference
reference is true or false false.
回答1:
I encountered this problem today, and come upon this Rails issue over at github. The exception seems to be thrown since the route url helper can't generate a valid for unsaved (invalid) records.
There's discussion on the github issue about allowing procs as an argument to the location parameter, but it doesn't look like it'll be added anytime soon.
For now I'll stick with using the following solution:
def create
@post = Post.new(params[:post])
if @post.save
respond_with(@post, location: edit_post_path(@post))
else
respond_with @post
end
end
回答2:
The only way I was able to solve is this:
def create
@problem = Problem.find(params[:problem_id])
@solution = @problem.solutions.build solution_params
success = @solution.save
respond_with(@solution) do |format|
format.html {redirect_to detail_problem_solution_path(@problem, @solution) } if success
end
end
来源:https://stackoverflow.com/questions/8190158/respond-with-is-redirecting-to-specified-location-even-on-validation-errors-in