2011-11-30 55 views
6

我使用RABL輸出太陽黑子/ 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 

回答

7

您可以充分控制與「節點」,避免這一問題完全是在「最壞」的情況:

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 

這是否幫助?

+0

感謝彌敦道 - 完美的工作!真的很感激這個幫助 - 而這個部分的東西讓事情變得非常乾淨。 – ejlevin1

+0

謝謝,這真的幫了我 –