Rails 多态关联,一类中有两种关联类型
考虑一个类:
class Link < ActiveRecord::Base
has_many :link_votes, :as => :vote_subject, :class_name => 'Vote'
has_many :spam_votes, :as => :vote_subject, :class_name => 'Vote'
end
问题是,当我使用 @link.link_votes << 添加新投票时Vote.new
的 vote_subject_type
是 'Link'
,而我希望它可以是 'link_votes'
或类似的东西。这是 AR 的限制还是有办法解决这个问题?
我实际上找到了一个相关的答案,但我不太确定它说的是什么: 同一模型上具有多个关联的多态关联
Consider a class:
class Link < ActiveRecord::Base
has_many :link_votes, :as => :vote_subject, :class_name => 'Vote'
has_many :spam_votes, :as => :vote_subject, :class_name => 'Vote'
end
The problem is, when I'm adding a new vote with @link.link_votes << Vote.new
the vote_subject_type
is 'Link'
, while I wish it could be 'link_votes'
or something like that. Is this an AR limitation or is there a way to workaround this thing?
I've actually found one related answer, but I'm not quite sure about what it says: Polymorphic Association with multiple associations on the same model
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想使用单表继承 - 这将允许您拥有两种不同类型的投票。这会将“类型”列添加到投票表中,然后您将按照这些方式作为 LinkVote 或 SpamVote 访问该
列。
在投票表中,您会看到如下列:
对性传播感染进行更多研究,我打赌您会找到答案。
Sounds like you want to use Single Table Inheritance - this will allow you to have two different types of Votes. This will add a 'type' column to the votes table that you will then access as a LinkVote or SpamVote
Along those lines.
In the votes table you'd see columns like:
Do more research on STI and I bet you'll find your answer.