我有兩種類,其中一種屬於另一種類,其中一種多態屬於另一種。雙向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 = t
和t.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
嗯,好的,點了。添加索引並擦除雙向`belongs_to`關聯。謝謝。 – unsorted 2011-01-22 14:09:52