Rails Newbie: Guidelines for Handling Errors in a Controller

Sorry if the question is obvious, I'm just starting to work with Rails.
Now I have the following code in several control methods:

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 for errors in all methods?
Is it recommended to use save!and process it in rescue_action?

Or do I need to make my own method respondand pass savein a block?

+5
source share
2 answers

, , . , .

def create
  @project.save!

  respond_to do |format|
    format.html { redirect_to(edit_project_url(@project), :notice => '#{user.name} added to #{role}.') }
    format.js
  end

rescue ActiveRecord::RecordInvalid
  respond_to do |format|
    format.html { render :action => "edit" }
    format.js #...
  end
end

, if , rescue .

def create
  Project.transaction do
    @project.save!
    @something_else.save!
    @other_stuff.save!
  end

  # ...
rescue ActiveRecord::RecordInvalid
  # ...
end

- , . , , , , .valid? , , , .

+16

if @object.save. , , rescue_from.

-

class MyController < ActionController::Base
  rescue_from ActiveRecord::RecordInvalid do
    render :action => edit
  end
end
+3

All Articles