Ruby on rails 双向属于(一个多态)
我有两种类,一种属于另一种,另一种属于多态性Ruby on rails 双向属于(一个多态),ruby-on-rails,polymorphic-associations,Ruby On Rails,Polymorphic Associations,我有两种类,一种属于另一种,另一种属于多态性 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 是的,你不是真的要做双向的关联。
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
是的,你不是真的要做双向的
关联。因此,当你在等式中添加多态性(这真的是一个词吗?)时,它将被打破
这些关系属于_,因为我希望在两个方向都能快速访问。我的印象是has_one关系会更慢,因为您必须查询相反的表来搜索匹配的_id
我不明白你为什么要这么做。如果你真的关心速度,你可以简单地索引所属的表上的外键列。速度差应该可以忽略不计 嗯,好的,我明白了。添加索引和擦除双向属于关联。谢谢
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