在我的控制器的索引操作中,我返回了一个应该呈现为 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 特定字段?
谢谢你,阿萨夫