在Rails控制器中的JSON输出中添加嵌套字段

时间:2014-02-11 23:13:07

标签: ruby-on-rails json ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

在标准Rails控制器的末尾有:

respond_to do |format|
  format.html
  format.json { render json: @cars }
end

按预期工作。除了JSON没有@cars

的关联
class Car < ActiveRecord::Base
  attr_accessible :model, :color
  belongs_to :manufacturer
end

JSON没有制造商的字段。如何让JSON拥有这些?我在belongs_to电话中添加了什么内容吗?有没有办法可以将它添加到从format.json创建的对象中?

2 个答案:

答案 0 :(得分:2)

默认情况下,将对象转换为JSON的方法as_json包含所有属性。但是manufacturer是一种方法。

您可以指示as_json向制造商添加:methods选项,请参阅api doc

所以你的Car模型可以像

一样
class Car < ActiveRecord::Base
  belongs_to :manufacturer

  def as_json(options={})
    super(options.merge methods: :manufacturer_json)
  end

  def manufacturer_json
    manufacturer.as_json
  end
end

包括制造商。

答案 1 :(得分:1)

我最喜欢的方法是使用Active Model Serializer gem.使用自定义序列化程序,您可以实现几乎任何您想要的JSON结构,除了使用Active Model Serializer for Has Many Through关联,目前正在进行大修。

您可能需要查看一些教程,例如http://robots.thoughtbot.com/fast-json-apis-in-rails-with-key-based-caches-and