开发者

Rails polymorphic associations, two assoc types in one class

开发者 https://www.devze.com 2022-12-15 05:11 出处:网络
Consider a class: class Link < ActiveRecord::Base has_many :link_votes, :as => :vote_subject, :class_name => \'Vote\'

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 addin开发者_JAVA技巧g 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号