How to convert this respond_to options to use Rail

2019-04-16 10:10发布

问题:

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 }