Brian
Brian

Reputation: 7135

Rails: Best approach for returning custom JSON from controller?

I'm looking for the best approach for returning json when the "show" action is called within my controller. I'm working with Rails 2.3.x.

There is some things I want to add and some I want to remove from the object before returning it, so simply doing one of these:

respond_to do |format|
  format.json {
    render :json => @object.to_json
  }
end

Won't necessarily work. I don't want everything in that object exposed. I was thinking I had two opeions here:

  1. Create a private helper method in the controller that builds a new object with only what I want in it, and send that along instead. The problem here is that I have a few views helper methods that I woudn't be able to use with this approach.
  2. Write out the json manually in a show.json.erb view. Problem here is it seems like I'm going against the grain and have to put in lots of logic to account for trailing commas and whatnot.

If this were HTML that I was returning instead, I would obviously just use a .html.erb file and only include what I want in there. But since I'm dealing with JSON, it seems like I should handle almost everything in code and not even deal with a views file.

Thoughts?

Upvotes: 0

Views: 599

Answers (1)

agronemann
agronemann

Reputation: 687

You should take a look at RABL (https://github.com/nesquena/rabl). Then you can build your show.json.rabl file like so:

object @person
attributes :id, :name, :age

Check out this RailsCast on RABL: http://railscasts.com/episodes/322-rabl

Also checkout https://github.com/rails/jbuilder - and the RailsCast: http://railscasts.com/episodes/320-jbuilder

Upvotes: 2

Related Questions