3

在我的控制器的索引操作中,我返回了一个应该呈现为 JSON 的图片模型数组。

def index
  @pictures = Pictures.all
  respond_to do |format|
    format.json { render json: @pictures.to_json( include: [:imageable] ) }
  end
end

该模型配置了多态关联。

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable

  attr_accessible :name
end

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable

  attr_accessible :type
end

图片数组将包括图片对象,该对象具有与员工和产品的可成像关联。如何以不同方式将可成像关联对象呈现为 json,包括 Employeee 和 Product 特定字段?

谢谢你,阿萨夫

4

1 回答 1

2

我建议您使用JBuilder 之类的东西来构建您的 json 响应。

然后,您使用您的逻辑创建一个名为 index.json.jbuilder 的模板文件来构建您的 json。

您将能够根据您的对象轻松构建您的 json。

例如:

json.array! @pictures do |picture|
  json.picture_attribute1 = picture.picture_attribute1
  json.picture_attribute2 = picture.picture_attribute2
  if picture.imageable.is_a?(Employee)
    json.employee_name = picture.imageable.name
  else
    json.product_name = picture.imageable.name
  end
end

请查看 JBuilder 的文档以了解如何使用它。

于 2013-06-25T11:46:47.983 回答