How to include associated objects using gon in Rails/jQuery

房东的猫 提交于 2019-12-23 03:31:59

问题


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.


回答1:


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.




回答2:


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]))


来源:https://stackoverflow.com/questions/9930684/how-to-include-associated-objects-using-gon-in-rails-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!