在我的 Item Controller 中,我希望在将其呈现为 JSON 之前向我的模型对象添加一个 transient (即非持久性)属性。
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。
最佳答案
我建议您自己构造要转换为 json 的对象。这既可以消除您在评论中遇到的问题,也可以防止您意外暴露您不想提供的信息。
类似于:
render :json => {
:item => {
:name => 'Some Item',
...
:comment => 'Some Comment
}
}
关于ruby-on-rails - ruby rails : Problem adding Transient Attribute to Object for JSON Serializaton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567779/