Mike Crittenden
Mike Crittenden

Reputation: 5917

Including acts_as_taggable_on tags in to_json output of a model

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.

Upvotes: 1

Views: 615

Answers (2)

monangik
monangik

Reputation: 366

In your favor model override as_json method.

def as_json(options={})
  super(:include => :tags)
end

Upvotes: 2

Bradley Priest
Bradley Priest

Reputation: 7458

You can pass options to the json call by calling to_json. Or by redefining as_json in your favor model.

render json: @favor.to_json(include: :tags)

Upvotes: 3

Related Questions