简体   繁体   中英

How to include associated objects using gon in Rails/jQuery

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.

Rails has a helpful as_json 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]))

If your @note.tags is a has_many association (not a simple array), gon 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 Rabl if you need to serialize too many AR objects, since gon supports Rabl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM