如何在rails3中自定义to_json方法? [英] How to customize the to_json method in rails3?
问题描述
我想将一个Place对象数组转换为json,我一直这样做:
I want to convert an array of Place objects to json, I've been doing it like this:
var places = <%= @places.to_json.html_safe %>;
唯一的问题是@places数组中的每个位置都有一个不相关的标记列表包括在内。我正在使用acts_as_taggable_on gem来处理标签,所以要获取一个地方的标签列表,我需要说place.tag_list。
The only problem is that every place in the @places array has an associated tag list that doesn't get included. I'm using the acts_as_taggable_on gem to handle tags, so to get the tag list for a place I need to say place.tag_list.
我该怎么办?获取javascript数组中每个位置的tag_list?我想我需要编写自己的to_json方法,但我不知道如何。
What do I have to do to get the tag_list included for each place in the javascript array? I think I'll need to write my own to_json method but I don't know how.
编辑
事实证明,这比我意识到的要容易。我能够这样说:
It turns out that this is easier than I realized. I was able to say this:
var places = <%= @places.to_json(:include => :tags).html_safe %>
唯一的问题是,这包含有关每个标签的更多信息,而不是我真正需要的。每个标签都有一个id和名称,我真正想要的只是一个带有标签名称的列表。
The only problem is that this includes more information about each tag than I really need. Every tag has an id and name, what I really want is just a list with tag names in it.
推荐答案
to_json
方法也接受一个名为<$ c $的参数C>方法。此参数允许您指定应调用并包含在对象的json表示中的方法。既然你提到你有一个名为 tag_list
的方法,你可以这样做:
The to_json
method also accepts an argument called methods
. This argument allows you to specify methods that should be called and included in the json representation of the object. Since you mentioned that you have a method called tag_list
, you can do this:
var places = <%= @places.to_json(:methods => :tag_list).html_safe %>
如果出于某种原因,您没有生成标签名称的方法,但每个标签有一个方法可以给你它的名字,你可以在你的 Place
模型中添加一个方法来生成一个标签名称列表,如下所示:
If, for some reason, you don't have a method to produce tag names, but each tag has a method to give you its name, you could add a method inside your Place
model to produce a list of tag names like so:
def tag_names
tags.collect do |tag|
tag.name
end
end
然后你就可以得到你的地方json与 tag_names
这样:
Then you could get your places json with tag_names
like this:
place_json = @places.to_json(:methods => :tag_names)
此技术适用于您所有的计算属性喜欢添加到模型的json表示。
This technique will work for any computed attributes you'd like to add to a model's json representation.
这篇关于如何在rails3中自定义to_json方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!