How to convert this respond_to options to use Rails 3 version?

萝らか妹 提交于 2019-12-22 00:07:46

问题


respond_to do |format|
  if @user.save
    format.js { render :nothing => true, :status => :ok, :location => @user }
  else
    format.js { render :json => @user.errors, :status => :unprocessable_entity }
  end
end

All options I've tried (like putting respond_to :js at the top of controller, etc) don't quite work the way as in this.


回答1:


Rails 3 Format:

Use respond_to :json and respond_with(@user)

  respond_to :json  # You can also add  , :html, :xml  etc.

  def create
    @user= User.new(params[:user])
      #---For html flash
      #if @user.save
      #  flash[:notice] = "Successfully created user."
      #end
    respond_with(@user)
  end

# Also, add :remote => :true, :format => :json to the form.



回答2:


Try using format.json instead of format.js in your controller and :remote => :true, :format => :json in corresponding form.

Though, I'm not quite sure whether format.json or format.js should be used in that case. As default scaffolding from Rails 3 generates controllers with format.json and you're doing render :json in response I believe format.json is the right way to go. And format.js should be used when you return a piece of JS that should be executed.




回答3:


The URL your are requesting should end with .json like this: /controller/action.json

If that is not possible:

You should set the 'accepts' parameter to 'application/json' while sending the ajax request.

Search for how to use 'accepts' here: http://api.jquery.com/jQuery.ajax/

And in the server side:

format.json { render :json => @user.errors, :status => :unprocessable_entity }


来源:https://stackoverflow.com/questions/8200929/how-to-convert-this-respond-to-options-to-use-rails-3-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!