开发者

Rails 3 - AJAX, response JS - How to Handle Errors

Given the following controller:

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

What's the Rails way of handling a .JS error response... Do I create .js file with开发者_Go百科 a different file name just for servering Errors?

Do I add an IF ELSE in the .js file?

thanks


It's been a while since this question was posted - but I just spent a while figuring this out & couldn't find too much help on this online, so:

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 

If seems that if you don't specify a file name, rails will look for create.js.erb in both cases (because format.js is called from create). This is not great in the case of success/error situations because you want different behaviour for each scenario - so override the filenames through the :action attribute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜