AnApprentice
AnApprentice

Reputation: 111080

How to build a json object

Right now in my thread controller I have the following

def thread
  @thread = Thread.find(params[:id])
  ....
  render :json => {"success" => 1}, :content_type => 'application/json'
end

What I'd like to do is build the json response to include @thread, but only some params so it's something like this:

{"success" => 1, "thread" => {"id": 1, "title": "hello world"}

Any idea how I can build this json object in the rails controller? Goal being to not include all the thread fields and to include success which is not a thread field?

Thanks

Upvotes: 0

Views: 328

Answers (3)

Chris Bailey
Chris Bailey

Reputation: 4136

you should use the model's as_json function.

render :json => {"success" => 1, :thread => @thread.as_json(:only => [:my, :wanted, :attributes]) }

as_json includes a large number of options to help you build a hash ready for JSON encoding including only, and except which will include all attributes on the model apart from the ones listed. methods which will add other methods available on the object and include to add associations (belongs_to, has_one, has_many etc) into the hash.

For more info examples see the as_json documentation at: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Upvotes: 3

rubyprince
rubyprince

Reputation: 17803

render :json => {"success" => 1, "thread" => @thread.attributes.select{ |k, v| ["id", "title"].include? k }}

Upvotes: 1

Dogbert
Dogbert

Reputation: 222418

How about

  render :json => {"success" => 1, "thread" => { "id" => @thread.id, "title" => @thread.title } }, :content_type => 'application/json'

Upvotes: 1

Related Questions