
Question:
I have a note and it has a certain number of attributes. It also has associated tags. I have been using gon to make this variable available to the javascript files of a page (making @note.attributes available to this page).
I can output the note attributes easily ie if I instantiate:
gon.note = @note.attributes
I can output its content:
alert(gon.note.content)
But, this doesn't put the notes' tags through.. I can't, for example, do :
alert(gon.note.tags)
What if I want to display a note's tags, but I want to bring them through with gon.note rather than make a whole other variable gon.tags. How might I do this (maybe some sort of joins or include)? I want to do this because it's better for, say, if you have multiple notes displaying.
Answer1:If your @note.tags
is a has_many
association (not a simple array), <a href="https://github.com/gazay/gon" rel="nofollow">gon</a> doesn't know how to serialize an array of Tag
instances.
You can do nothing but introduce another variable:
# controller
gon.note_tags = @note.tags.map &:attributes
# JS
var first_tag_name = gon.note_tags[0].name;
You may want to use <a href="https://github.com/nesquena/rabl" rel="nofollow">Rabl</a> if you need to serialize too many AR objects, since gon supports Rabl.
Answer2:Rails has a helpful <a href="http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json" rel="nofollow">as_json</a> method that lets you specify your associations, which fields to include, and even methods to include. It returns a ruby hash for single objects or an array for collections, and this will get nicely serialized when gon calls to_json on it.
gon.note = @note.as_json(:include => [:tags]))