ruby-on-rails - 在 Rails JSON 序列化中重命名模型关联属性?

标签 ruby-on-rails json serialization activerecord ruby-on-rails-3

我有一个现有的 Rails 3 应用程序,我正在向其中添加一个 JSON API。我们有一个 Vendor ActiveRecord 模型和 Employee事件记录模型。一个 Employee属于 Vendor .在 API 中,我们希望包含一个 EmployeeVendor在 JSON 序列化中。例如:

# Employee as JSON, including Vendor
:employee => {
    # ... employee attributes ...
    :vendor => {
        # ... vendor attributes ...
    }
}

这很容易。但是,我有一个业务要求,即公共(public) API 不公开内部模型名称。也就是说,对于外界来说,它需要看起来好像 Vendor模型实际上称为 Business :
# Employee as JSON, including Vendor as Business
:employee => {
    # ... employee attributes ...
    :business => {
        # ... vendor attributes ...
    }
}

对于顶级对象,这很容易做到。也就是说,我可以调用@employee.as_json(:root => :dude_who_works_here)重命名 EmployeeDudeWhoWorksHere在 JSON 中。但是对于包含的关联呢?我尝试了一些没有成功的事情:
# :as in the association doesn't work
@employee.as_json(:include => {:vendor => {:as => :business}})

# :root in the association doesn't work
@employee.as_json(:include => {:vendor => {:root => :business}})

# Overriding Vendor's as_json doesn't work (at least, not in a association)
    # ... (in vendor.rb)
    def as_json(options)
        super(options.merge({:root => :business}))
    end
    # ... elsewhere
    @employee.as_json(:include => :vendor)

我唯一的另一个想法是手动重命名 key ,如下所示:
# In employee.rb
def as_json(options)
    json = super(options)
    if json.key?(:vendor)
        json[:business] = json[:vendor]
        json.delete(:vendor)
    end
    return json
end

但这似乎不优雅。我希望有一种更清洁、更符合 Rails 的方式来做我想做的事。有任何想法吗?

最佳答案

尝试使用 as_json 的内置选项生成复杂的 JSON 很笨拙。我会覆盖 as_json在您的模型中,而不必为调用 super 而烦恼一点也不。为 as_json 制作您自己的选项键控制要包含在哈希中的内容。

# employee.rb
def as_json(options = {})
  json = {:name => name, ...} # whatever info you want to expose
  json[:business] = vendor.as_json(options) if options[:include_vendor]
  json
end

关于ruby-on-rails - 在 Rails JSON 序列化中重命名模型关联属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455613/

相关文章:

javascript - 在 Windows 和 Ubuntu 计算机之间开发 ROR

ruby-on-rails - 在 create.js.erb 中重定向

json - swift json 如何填充一个对象

c# - 如何使用 JSONCONVERT 序列化由 C# 中类本身的实例初始化的类的静态变量

php - 根据另一个表或字段中的数组中的记录保存 id

JSON 反序列化仅在实时构建中抛出循环引用

mysql - Ruby on Rails 与 Xampp

ruby-on-rails - 如何启用 :tsearch dictionary for pg_search multi-search?

java - 如何将 JSONObject 转换为 gson.JsonObject?

javascript - 防止在单击事件中重复调用异步加载函数