3

I'm looking to have a model that gets created / updated via AJAX. How do you do this in Ruby on Rails?

Also, more specifically: how do you output JSON in RoR?

def create
  response = {:success => false}
  @source = Source.new(params[:source])
  if @source.save
    response.success = true
  end
  render :json => response.to_json
end

3 Answers 3

8

All you need to do is call render :json with an object, like so:

render :json => my_object

For most objects, this will just work. If it's an ActiveRecord object, make sure to look at as_json to see how that works. For your case illustrated above, your hash will be transformed to json and returned.

However, you do have an error: you cant access the success key via response.success -- you should instead do response[:success]

Sign up to request clarification or add additional context in comments.

Comments

3

jimothy's solution is really good butI believe it isn't scalable in the long term. Rails is meant to be a model, view, and controller framework. Right now JSON is cheated out of a view in default rails. However there's a great project called RABL which allows JSON view. I've written up some arguments for why I think it's a good option and how to get up and running with it quickly. See if this is useful for you: http://blog.dcxn.com/2011/06/22/rails-json-templates-through-rabl/

2 Comments

+1 on RABL. I've been using it on my first real RoR project (an API service) and it has worked very well. The only issue so far was to do with serializing date time objects, and a workaround solution has been added to the RABL github read me file.
Yeah! It makes a lot more sense for scallable apps.
0
@source = Source.new(params[:source])

respond_to do | f |
  f.html {
    # do stuff to populate your html view
    # maybe nothing at all because @source is set
  }

  f.any(:xml, :json) { 
    render request.format.to_sym => @source 
  }
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.