Reputation: 9109
I am working with backbone.js as front end that receives a json result from controller like this
def index
myEntry = Entry.all
respond_with myEntry.to_json()
end
The resulting json arrays is collection of objects as follows
0:Object
id:1
name:matz
1:object
id:2
name: hilary
Now i have for each name an extra tag field that is stored using act-as-taggable-on gem. To access the tag of any entry i would have to use Entry.find(1).tag_list. I would like to append the result of each tag to its respective object from above, to get result something like this
0:Object
id:1
name:matz
tag:friend,rich
1:object
id:2
name: hilary
tag:intelligent
Upvotes: 3
Views: 2347
Reputation: 9109
Perfect answer from @dimakura. But if you wanted to include something to your json array that was somehow not directly connected to your result, or for more complex reasons, here is another way
Example Code
myEntry = Entry.all
myhash = []
myEntry.each do |index|
myhash << {name: index.name,tag_list: index.tag_list}
end
respond_with myhash.to_json
Upvotes: 2
Reputation: 7655
This should work for you:
render json: User.all.to_json(include: :tags)
or alternatively (just tag names):
render json: User.all.to_json(methods: :tag_list)
Upvotes: 2