Sorry if the question is obvious, I am only starting to work with Rails.
I have a following code in several controller methods now:
respond_to do |format|
if @project.save
format.html { redirect_to(edit_project_url(@project), :notice => '#{user.name} added to #{role}.') }
format.js
else
format.html { render :action => "edit" }
format.js #...
end
end
So the question is, what is the best way to do the same thing for errors in all methods?
Is it recommended that I use save! and handle it in rescue_action?
Or should I do my own respond method and pass save in a block?
It’s often more convenient to use the exception-raising variant of save and rescue that later in the block than to branch like that. The advantage to exceptions is they’ll bust out of transactions.
You’ll find that it gets really tricky to wrangle your way out of a pile of nested
ifstatements when trying to save more than one object at a time, but a simplerescuefor exceptions will handle it neatly.If any one of those saves blows up you’ll get an exception. To ensure that all of them are displaying validation errors you might have to call
.valid?on each to prime them or you will have those after the failure left untested.