gpt4 book ai didi

ruby-on-rails - 将 rails 多态关联对象呈现为 JSON

转载 作者:行者123 更新时间:2023-12-04 05:55:23 26 4
gpt4 key购买 nike

在我的 Controller 的索引操作中,我返回了一个应该呈现为 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 特定字段?

谢谢你,阿萨夫

最佳答案

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

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

您将能够根据您的对象轻松构建您的 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 的文档以了解如何使用它。

关于ruby-on-rails - 将 rails 多态关联对象呈现为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17296111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com