I’m using acts_as_taggable_on in my rails app. I’d like these tags to show up in the to_json representation of my model.
For example, to_json of one instance of my model looks like this:
{"created_at":"2012-02-19T03:28:26Z",
"description":"Please!",
"id":7,
"points":50,
"title":"Retweet this message to your 500+ followers",
"updated_at":"2012-02-19T03:28:26Z"}
…and I’d like it to look something like this:
{"created_at":"2012-02-19T03:28:26Z",
"description":"Please!",
"id":7,
"points":50,
"title":"Retweet this message to your 500+ followers",
"updated_at":"2012-02-19T03:28:26Z"
"tags" :
{"id":1,
"name":"retweet"},
{"id":2,
"name":"twitter"},
{"id":3,
"name":"social"}
}
My controller code is just the default that scaffolding gives me:
def show
@favor = Favor.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @favor }
end
end
Note that I can already access @favor.tags in the template, and @favor.tags.to_json works as expected, I just needed that data to be included when outputting @favor.to_json.
You can pass options to the json call by calling
to_json. Or by redefiningas_jsonin your favor model.render json: @favor.to_json(include: :tags)