关于Rails关联关系输出json的问题

我在rails中,使用了acts_as_taggable来实现tag功能。

现在,在controller中,我用了下列代码获取所有照片

[code="ruby"]
def get_photos
respond_to do |format|
format.json { render :text => Photo.find(:all).to_json }
end
end
[/code]

正常情况下,我可以通过
@photo.tags 获取照片的标签

但是现在我获取的是json格式,返回的json数据,只有Photo对象的内容,并没有tags的相关信息

如下:

[{"photo": {"created_at": "2009-06-08T20:05:48Z", "id": 1, "path": "test.jpg", "title": "test", "updated_at"
: "2009-06-08T20:05:52Z"}}, {"photo": {"created_at": "2009-06-08T20:06:32Z", "id": 2, "path": "test2
.jpg", "title": "fre", "updated_at": "2009-06-08T20:06:35Z"}}, {"photo": {"created_at": "2009-06-08T12
:40:25Z", "id": 3, "path": "2009_06_08_20_40_25_Creek.jpg", "title": "xxx", "updated_at": "2009-06-08T12
:40:25Z"}}, {"photo": {"created_at": "2009-06-08T12:55:23Z", "id": 4, "path": "2009_06_08_20_55_23_Humpback
Whale.jpg", "title": "dcj", "updated_at": "2009-06-08T12:55:23Z"}}]

请问如何让返回的json数据包含tag?
[b]问题补充:[/b]
Photo.find(:all, :inlcude => [xx]).to_json

尝试过了,不行。

2个回答

Sorry 是我记错了

include 在后面

http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001826

konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
"created_at": "2006/08/01", "awesome": true,
"posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
{"id": 2, author_id: 1, "title": "So I was thinking"}]}

Photo.find(:all).to_json

->

Photo.find(:all, :inlcude => [xx]).to_json

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问