【发布时间】:2011-04-03 19:48:01
【问题描述】:
在我的 Item 控制器中,我希望在将模型对象呈现为 JSON 之前为其添加一个瞬态(即非持久)属性。
def show
@item = Item.find(params[:id])
@item.comment = "some comment"
render :json => @item
end
我的 Item 类如下所示:
class Item < ActiveRecord::Base
attr_accessor :comment
@comment
结束
我的问题是评论实例变量没有在 JSON 中呈现。持久的所有内容都出现在 JSON 输出中。我是否需要重写 to_json 方法才能使其工作?或者有没有更简单的方法来确保评论在 JSON 输出中呈现?
感谢您的帮助。
------------- 更新
这是从 Chubas 建议演变而来的解决方案。覆盖 Item 上的 to_json 方法:
def to_json(options = {})
options[:methods] = :comment;
super(options)
end
很想知道这是否与你的想法一致,Chubas。
【问题讨论】:
-
另见...“您通常希望不理会 to_json,因此您需要做的就是添加自己的 as_json 实现,就像这样...”stackoverflow.com/questions/6892044/…
标签: ruby-on-rails ruby json