3

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

  • Create an empty array
  • Loop through your result array
    • In each of loop append to the array your required hash value
  • Return array converted into json

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.