Ruby on rails 多模型集合

Ruby on rails 多模型集合,ruby-on-rails,ruby,rabl,Ruby On Rails,Ruby,Rabl,我使用RABL输出一个Sunspot/SOLR结果集,搜索结果对象由多个模型类型组成。目前在rabl视图中,我有: object false child @search.results => :results do attribute :id, :resource, :upccode attribute :display_description => :description code :start_date do |r| r.utc_start_date.t

我使用RABL输出一个Sunspot/SOLR结果集,搜索结果对象由多个模型类型组成。目前在rabl视图中,我有:

object false

child @search.results => :results do
  attribute :id, :resource, :upccode
  attribute :display_description => :description

  code :start_date do |r|
    r.utc_start_date.to_i
  end

  code :end_date do |r|
    r.utc_end_date.to_i
  end

end

child @search => :stats do
  attribute :total
end
上述方法适用于单个模型;但是,当@search.results集合中有多个模型类型时,它会失败,因为这两个类没有相同的实例方法。有人知道如何根据类型拥有不同的属性吗?最终,最好根据对象的类型在结果集合中有条件地扩展不同的模板。类似于下面的伪代码:

child @search.results => :results do |r|
  if r.class == Product
    extends "product/base"
  else
    extends "some other class base"
  end
end

您可以完全控制“节点”,并在“最坏”的情况下完全避免此问题:

node :results do
  @search.results.map do |r|
    if r.is_a?(Product)
      partial("product/base", :object => r)
    else # render other base class
      partial("other/base", :object => r)
    end
  end
end

这有帮助吗?

谢谢内森——这很有效!真的很感谢你的帮助,而且部分的东西让事情变得非常干净。谢谢,这真的帮了我的忙