在rails中使用jbuilder构建不同类的对象数组

Using jbuilder in rails to construct an array of objects with different classes

我的 rails 应用程序中的模型 (FirstModel) 与另一个模型 (Item) 有 has_many 关系。

class FirstModel < ActiveRecord::Base

  has_many :items, :dependent => :destroy

  def item_array
    a = []
    self.items.each do |item|
      a.push(item.item_thing)
    end
    a
  end
end

项目本身属于 :item_thing 通过多态关联。 FirstModel returns 的一个方法 "items",不是连接模型对象(属于 class Item),而是每个 Item 对象的 item_thing,因此它是不同 classes 的对象数组(在 rails 控制台中检查,方法 returns 数组就好了)

class Item < ActiveRecord::Base
  belongs_to :item_thing,  :polymorphic => true


end

在我的 FirstModel show.json.jbuilder 中,我想获取 "items" 的数组,并根据项目所属的 class 使用不同的模板。下面的文件路径是"views/api/items/show.jbuilder"

json.extract! @item, :name

json.items @item.item_array do |item|
  if item.class == 'Book'
    json.partial! 'api/books/show', item
  end
  if item.class == 'Car'
    json.partial! 'api/cars/show', item
  end
end

汽车和书籍模板路径为"views/api/cars/show.json.jbuilder"和“views/api/books/show.json.jbuilder.

当我从上面的模板中获取 json 时,FirstModel 对象的名称可见,项目数组为空,而我试图为每个项目获取一个哈希数组,通过其各自的呈现模板。

感谢您的帮助!

如果您将 class 字符串更改为实际的 class 名称,我认为您的代码将有效。

User 而不是 "User"

或者您可以保留字符串并使用 .class.to_s,这将 return "User" 用于用户记录。

如果您对元编程感兴趣,activesupport 中的 constantizecamelifyunderscore 方法可能会很有用。

如果您正确命名您的项目和部分,您可能只需执行类似下面的代码的操作。

json.items @item.item_array do |item|
  json.partial! "api/#{item.class.to_s.pluralize.downcase}/show"
end

或者,您可以在 item.class.to_s 上使用 case 语句,或者作为建议的其他答案之一,使用 class 实际 class 而不是 class 名称作为字符串。