Rails 多态关联,一类中有两种关联类型

发布于 2024-08-15 20:34:03 字数 616 浏览 9 评论 0原文

考虑一个类:

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.newvote_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抹茶夏天i‖ 2024-08-22 20:34:03

听起来您想使用单表继承 - 这将允许您拥有两种不同类型的投票。这会将“类型”列添加到投票表中,然后您将按照这些方式作为 LinkVote 或 SpamVote 访问该

class SpamVote << Vote
  ...
end

列。

class Link < ActiveRecord::Base

  has_many :link_votes, :as => :vote_subject
  has_many :spam_votes, :as => :vote_subject

end

在投票表中,您会看到如下列:

id, type, vote_subject_type, vote_subject_id, etc.

对性传播感染进行更多研究,我打赌您会找到答案。

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

class SpamVote << Vote
  ...
end

Along those lines.

class Link < ActiveRecord::Base

  has_many :link_votes, :as => :vote_subject
  has_many :spam_votes, :as => :vote_subject

end

In the votes table you'd see columns like:

id, type, vote_subject_type, vote_subject_id, etc.

Do more research on STI and I bet you'll find your answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文