本文介绍了如何在Rails/jQuery中使用gon包含关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注释,它具有一定数量的属性.它还具有关联的标签.我一直在使用gon使此变量可用于页面的javascript文件(使@ note.attributes可用于此页面).

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

我可以输出其内容:

 alert(gon.note.content)

但是,这不能使便笺的标签通过..例如,我不能做:

But, this doesn't put the notes' tags through.. I can't, for example, do :

 alert(gon.note.tags)

如果我想显示一个笔记的标签,但是我想通过gon.note使它们通过而不是使整个其他变量成为gon.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.

推荐答案

如果您的@note.tagshas_many关联(不是简单的数组),则 gon 不知道如何序列化Tag实例的数组.

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;

如果您需要序列化太多的AR对象,则可能要使用 Rabl ,因为gon支持Rabl

You may want to use Rabl if you need to serialize too many AR objects, since gon supports Rabl.

这篇关于如何在Rails/jQuery中使用gon包含关联对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:15