How to build a json object
Right now in my thread controller I have the following
def thread
@thread = Thread.find(params[:id])
....
re开发者_Go百科nder :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_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
How about
render :json => {"success" => 1, "thread" => { "id" => @thread.id, "title" => @thread.title } }, :content_type => 'application/json'
render :json => {"success" => 1, "thread" => @thread.attributes.select{ |k, v| ["id", "title"].include? k }}
精彩评论