Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you output JSON from Ruby on Rails?

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
like image 374
Geoff Avatar asked Dec 08 '25 01:12

Geoff


2 Answers

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]

like image 70
jimothy Avatar answered Dec 10 '25 16:12

jimothy


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/


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!