ruby on rails has_many :through association which has two columns with same model

陌路散爱 提交于 2019-12-10 10:08:39

问题


I have the following model:

class UserShareTag < ActiveRecord::Base
  attr_protected :sharee_id, :post_id, :sharer_id

  belongs_to :sharer, :class_name => "User"
  belongs_to :post
  belongs_to :sharee, :class_name => "User"

  validates :sharer_id, :presence => true
  validates :sharee_id, :presence => true
  validates :post_id, :presence => true
end

In the Post model, I have the following line:

has_many :user_share_tags, :dependent => :destroy
has_many :user_sharers, :through => :user_share_tags, :uniq => true, :class_name => "User"
has_many :user_sharees, :through => :user_share_tags, :uniq => true, :class_name => "User"

How do I convey that :user_sharers should correspond to :sharer_id? and :user_sharees should correspond to :sharee_id? Since they both are the same User model, I am unsure what to do.

Somewhat related problem - in the User model I have:

has_many :user_share_tags, :dependent => :destroy
has_many :user_shared_posts, :through => :user_share_tags, :uniq => true, :class_name => "Post"
has_many :recommended_posts, :through => :user_share_tags, :uniq => true, :class_name => "Post"

How do I incorporate the additional logic that :user_shared_posts should contain the posts where the :sharer_id is the user_id? and :recommended_posts should contain the posts where the :sharee_id is the user_id?

Thanks in advance!


回答1:


You just need to add a :source parameter to your has_many associations (and you don't need the :class_name option):

has_many :user_sharers, :through => :user_share_tags, :source => :sharer, :uniq => true, :class_name => "User"
has_many :user_sharers, :through => :user_share_tags, :source => :sharee, :uniq => true, :class_name => "User"

Then in your User model, you need an extra has_many association:

has_many :user_share_tags_as_sharee, :class_name => "UserShareTag", :foreign_key => :sharee_id, :dependent => :destroy
has_many :user_share_tags_as_sharer, :class_name => "UserShareTag", :foreign_key => :sharer_id, :dependent => :destroy
has_many :user_shared_posts, :source => :post, :through => :user_share_tags_as_sharer, :uniq => true
has_many :recommended_posts, :source => :post, :through => :user_share_tags_as_sharee, :uniq => true


来源:https://stackoverflow.com/questions/6195916/ruby-on-rails-has-many-through-association-which-has-two-columns-with-same-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!