我在我的rails应用中使用acts_as_taggable_on。我希望这些标签显示在我的模型的to_json表示中。
例如,我的模型的一个实例的to_json看起来像这样:
{"created_at":"2012-02-19T03:28:26Z",
"description":"Please!",
"id":7,
"points":50,
"title":"Retweet this message to your 500+ followers",
"updated_at":"2012-02-19T03:28:26Z"}
...我希望它看起来像这样:
{"created_at":"2012-02-19T03:28:26Z",
"description":"Please!",
"id":7,
"points":50,
"title":"Retweet this message to your 500+ followers",
"updated_at":"2012-02-19T03:28:26Z"
"tags" :
{"id":1,
"name":"retweet"},
{"id":2,
"name":"twitter"},
{"id":3,
"name":"social"}
}
我的控制器代码只是脚手架给我的默认代码:
def show
@favor = Favor.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @favor }
end
end
请注意,我已经可以在模板中访问@ favor.tags了,@ favor.tags.to_json按预期工作,我只需要在输出@ favor.to_json时包含这些数据。
答案 0 :(得分:3)
您可以通过调用to_json
将选项传递给json调用。或者在您的青睐模型中重新定义as_json
。
render json: @favor.to_json(include: :tags)
答案 1 :(得分:2)
在您的青睐模型中覆盖 as_json
方法。
def as_json(options={})
super(:include => :tags)
end