6

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
4

1 に答える 1

8

「ノード」を使用して完全に制御し、「最悪」の場合にこの問題を完全に回避できます。

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

それは役に立ちますか?

于 2011-11-30T19:27:00.557 に答える