双向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
时,我运行 after_save 方法,该方法创建术语 t
,使得 c.term = t
和 <代码>t.reference = c。不过,这看起来像是一种黑客行为……有没有办法自动告诉 Rails 这种关系存在,并且设置 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
I have two kinds of classes, one of which belongs_to the other kind, and one of which polymorphically belongs to the other kind.
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
The relationships are belongs_to because I want fast access in both directions. I'm under the impression that the has_one
relationship would be slower because you would have to query the opposite table to search for a matching _id
.
Right now, when I create a course c
, I run an after_save method which creates a term t
such that c.term = t
and t.reference = c
. This seems like kind of a hack though... is there any way to automatically tell rails that this relationship exists and that setting c.term = t
should automatically make t.reference = c
?
I know that with polymorphic associations you can specify the :as
attribute (see the API), but it looks like this doesn't work for 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您并不是真的要进行双向
belongs_to
关联。因此,当您将多态性(这真的是一个词吗?)添加到等式中时,它就会崩溃。我不明白你为什么要这样做。如果您确实关心速度,则只需在
belongs_to
表上对foreign_key 列建立索引即可。速度差异应该可以忽略不计。Yeah, you're not really meant to do bi-directional
belongs_to
associations. As such, when you add polymorphicality (is that really a word?) into the equation, it will break.I don't see why you'd want to do this. If you're really concerned with speed, you can simply index the foreign_key column(s) on the table that
belongs_to
. The speed difference should be negligible.