在标准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
创建的对象中?
答案 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