ruby-on-rails - ruby rails : Problem adding Transient Attribute to Object for JSON Serializaton

标签 ruby-on-rails ruby json

在我的 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/

相关文章:

ruby-on-rails - 如何使用 Ruby gem 添加产品变体

ruby-on-rails - 旧 Rails 应用程序出现奇怪的 Rails 错误 "permission denied: bin/rails"

jquery - 未捕获的类型错误 :Undefined is not a function

ruby-on-rails - Javascript 库不适用于 heroku

Ruby 习语 : method call or else default

ruby-on-rails - Gem::LoadError:尝试在 Heroku 上部署时 - Rails 4

java - 如何使用GSON获取解析后的数据

ios - 在swift中使用字典的不同数据类型?

ruby-on-rails - rails 教程 : Putting flash messages in partial yields error "undefined method ` each' for nil:NilClass"?

ruby-on-rails - 代表 RoR 的一年?