Rails 3 - AJAX, JS Answer - How to Deal with Errors

Given the following controller:

def create
      if @mymodel.save
        format.js
      else
        format.js   { render :js => @mymodel.errors }
      end
end

What is the Rails way to handle a .JS error response ... Am I creating a .js file with a different file name for server errors only?

Am I adding IF ELSE to a .js file?

thank

+5
source share
1 answer

Some time passed since this question was published, but I just took some time to figure it out and could not find too much help in this online mode, therefore:

The solution is to create .js.erb files - one for success and one for failure.

  def create
    @foo = Foo.new(params[:foo])
    if @foo.save
      respond_to do |format|
          format.html { redirect_to root_path }
          format.js   { render :action => "success"}  #rails now looks for success.js.erb
        end
    else
      respond_to do |format|
        format.html { render :action => 'new'}
        format.js   { render :action => "failure"}  #rails now looks for failure.js.erb
      end
    end
  end
end 

, , create.js.erb ( format.js create). /, - action.

+8

All Articles