开发者

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

开发者 https://www.devze.com 2023-03-10 01:47 出处:网络
I have the following model: class UserShareTag < ActiveRecord::Base attr_protected :sharee_id, :post_id, :sharer_id

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 wher开发者_运维百科e the :sharee_id is the user_id?

Thanks in advance!


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
0

精彩评论

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