2014-10-29 49 views
0

元素可以通過多態關聯元素與不同模型關聯。因爲我想要使用嵌套窗體,所以我必須爲不同的模型建立關聯(關聯element_recommendation)。未更改的關聯條件

下面的代碼按預期工作:

class Element < ActiveRecord::Base  
    belongs_to :elementable, :polymorphic => true, :dependent => :destroy 

    belongs_to :element_recommendation, ->(element) { 
    if element.elementable_type == 'ElementRecommendation' 
    where('true = true') 
    else 
    none 
    end }, :class_name => "ElementRecommendation", :foreign_key => "elementable_id" 
    [..] 

但是我不滿意在element_recommendation協會拉姆達。這是一個全或無關聯。 - 部分是可識別的,但將其視爲-部分不明顯。我怎樣才能讓其中('true = true')可識別?

回答

0

我發現當我在寫這個問題的解決:

belongs_to :element_recommendation, ->(element) { 
    if element.elementable_type == 'ElementRecommendation' 
    self 
    else 
    none 
    end }, :class_name => "ElementRecommendation", :foreign_key => "elementable_id"