1
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.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Jacob
  • 6,317
  • 10
  • 40
  • 58

3 Answers3

4

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.
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 1
    Is it a security risk to return the entire object model (since the user could see all the data using firebug console)? -- I ask because most models would have boolean fields that you'd store also -- and might not be best to show the user. – Jacob Nov 20 '11 at 16:15
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.

KL-7
  • 46,000
  • 9
  • 87
  • 74
1

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 }
Arun Kumar Arjunan
  • 6,827
  • 32
  • 35