ruby-on-rails - Rails 中 to_json 的默认值为 :include

标签 ruby-on-rails json

假设我有一个属于用户的模型帖子。要转换为 json,我会这样做

@reply.to_json(:include => {:user => {:only => [:email, :id]}, 
               :only => [:title, :id])

但是,我想为此设置一些默认值,因此我不必每次都指定 :only。我正在尝试覆盖 as_json 来完成此操作。当我在用户模型中添加 as_json 时,当我执行 @user.to_json 时会调用它,但当用户包含在 @reply.to_json 中时,我为用户覆盖的 as_json 将被忽略。

我该如何进行这项工作?

谢谢

最佳答案

您可以通过覆盖模型中的 serializable_hash 来做到这一点,如下所示:

class Reply < ActiveRecord::Base
  def serializable_hash(options={})
    options = { 
      :include => {:user => {:only => [:email, :id]}, 
      :only => [:title, :id]
    }.update(options)
    super(options)
  end
end

这将影响所有可序列化的方法,包括 serializable_hashto_jsonto_xml

关于ruby-on-rails - Rails 中 to_json 的默认值为 :include,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5000870/

相关文章:

java - 转换为 JSON 字符串时扩展类中的数据丢失

ruby-on-rails - 将 Cardmagic gem 集成到 Rails 应用程序中

ruby-on-rails - 表单标签只传递一个值而不是多个

ruby-on-rails - Ruby - 从哈希数组中提取特定键的值

jquery - jquery load 方法是否提供与 Rails Replace_html 方法等效的 ajax 功能?

javascript - Google Books API JSON 对象问题

ruby-on-rails - 如何防止 Rails 的列名出现 "pluralizing"错误?

javascript - 使用 JSON 中的 header 从 JSON 创建对象

json - as_json 运行速度非常慢(Mongoid + Sinatra)

java - 调用 readValue 时出现 Json NullPointerException