2012-06-26 46 views
3

我有一個數據模型,其中User可以像Project, Suggestion, Comment或其他對象。 如果我們只是爲了支持Project孩子渲染具有多態模型的RABL部分

object @like 
attributes :id, :created_at, :target_type, :target_id, :user_id 
child :user => :user do 
    extends "users/show" 
end 
child :target do 
    node do |project| 
    partial('projects/show', :object => project) 
    end 
end 

不過,我希望能夠用以及因target_typesuggestions/show, comments/show諧音的模型設置正確,並likes/show.rabl作品。

我試過,但它不工作:

child :target do |u| 
    u.target.map do |r| 
    if r.is_a?(Suggestion) 
     partial("suggestions/show", :object => r) 
    elsif r.is_a?(Project) 
     partial("projects/show", :object => r) 
    end 
    end 
end 

我得到undefined method target for <Rabl::Engine:0x69fb988>。但是,在第一種情況下,我沒有看到這個錯誤。有任何想法嗎?

回答

3

您是否嘗試過使用extends而不是partial

也許你可以嘗試這樣的事情?

child :target do |u| 
    u.target.map do |r| 
    if r.is_a?(Suggestion) 
     extends "suggestions/show" 
    elsif r.is_a?(Project) 
     extends "projects/show" 
    end 
    end 
end 

在這種情況下,當您使用extends,你不需要在:object通過,因爲你在與對象r通過迭代的範圍是已。

1

還有另一種方式來做到這一點,你就不必列出所有可能的多態關係。這可能有點冒失,但它的工作原理。

像這樣:

child :target do |u| 
    # The regexp snippet selects everything from the last/and to the end 
    extends u.to_partial_path.gsub(/\/([^\/]+)$/, '/show') 
end 

,它使用了對象的.to_partial_path。如果您的對象名爲Suggestion,則.to_partial_path將返回suggestions/suggestion。這就是爲什麼我使用gsub()來代替/後跟/show

使用此解決方案,您不必在每次添加另一個多態關係時更新此文件。您只需確保新物件有一個稱爲show.json.rabl