2011-01-19 28 views
0

我有兩種類,其中一種屬於另一種類,其中一種多態屬於另一種。雙向belongs_to(一個多態)

class Term < ActiveRecord::Base 
    belongs_to :reference, :polymorphic => true 
end 

class Course < ActiveRecord::Base 
    belongs_to :term 
end 

class Career < ActiveRecord::Base 
    belongs_to :term 
end 

這些關係是belongs_to,因爲我想要在兩個方向上快速訪問。我覺得has_one關係會比較慢,因爲你必須查詢對面的表來搜索匹配的_id

現在,當我創建一個過程c,我運行它創建t這樣c.term = tt.reference = c術語的after_save的方法。這似乎是一種黑客,雖然...有什麼辦法可以自動告訴軌道,這種關係存在,並設置c.term = t應該自動t.reference = c

我知道,通過多態關聯可以指定:as屬性(請參閱API),但看起來這對於belongs_to不起作用。

class Asset < ActiveRecord::Base 
    belongs_to :attachable, :polymorphic => true 

    def attachable_type=(sType) 
     super(sType.to_s.classify.constantize.base_class.to_s) 
    end 
    end 

    class Post < ActiveRecord::Base 
    # because we store "Post" in attachable_type now :dependent => :destroy will work 
    has_many :assets, :as => :attachable, :dependent => :destroy 
    end 

回答

1

是的,你不是真的打算做雙向belongs_to協會。因此,當你在等式中添加多態性(這真的是一個單詞嗎?)時,它會中斷。

這些關係是belongs_to,因爲我想在兩個方向上快速訪問。我覺得has_one關係會比較慢,因爲你必須查詢相反的表來搜索匹配的_id。

我不明白你爲什麼要這樣做。如果你真的關心速度,你可以簡單地索引belongs_to表上的foreign_key列。速度差異應該可以忽略不計。

+0

嗯,好的,點了。添加索引並擦除雙向`belongs_to`關聯。謝謝。 – unsorted 2011-01-22 14:09:52