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
you should use the model’s
as_jsonfunction.as_json includes a large number of options to help you build a hash ready for JSON encoding including
only, andexceptwhich will include all attributes on the model apart from the ones listed.methodswhich will add other methods available on the object andincludeto 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