开发者

respond_to change response type

开发者 https://www.devze.com 2023-01-08 03:15 出处:网络
I am calling a controller\'s create action via ajax so when the object saves successfully, the js response is triggered. However, if the obje开发者_如何学Cct fails to save due to validation, then I wa

I am calling a controller's create action via ajax so when the object saves successfully, the js response is triggered. However, if the obje开发者_如何学Cct fails to save due to validation, then I want the response to be html. I hope to achieve this by not returning the js response in the else block (please see code below) but this produces a 406 Not Acceptable error.

Any ideas on how to do this?

I should also probably note that the reason why I want to do this is because I am unsure how to create an appropriate js response if the validation fails...

Thanks in advance!!! =]

Controller create action

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    format.html { redirect_to(@person) }
    format.js
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end


If you are specifically requesting the js format in the URL, then you have to provide JS for your response. One option instead would be to not specify a format in the request, and then just filter your responses for xhr. Like so:

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    if request.xhr?
      format.js
    end
    format.html { redirect_to(@person) }
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end

This way, if you make a request without specifying ANY format, it will hit js first, IF it's an xhr request (ie, an AJAX request), whereas, if there is an error, it will return html, no matter what.

Does that make sense?

0

精彩评论

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