【问题标题】:Rendering rails polymorphic association object to JSON将rails多态关联对象渲染为JSON
【发布时间】:2013-06-25 11:29:59
【问题描述】:

在我的控制器的索引操作中,我返回了一个应该呈现为 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

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

谢谢你, 阿萨夫

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 polymorphic-associations


    【解决方案1】:

    我建议您使用 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的文档了解如何使用它。

    【讨论】:

    • 好方法!让我深入了解 jbuilder。
    猜你喜欢
    • 2011-03-28
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多