Ruby on rails has_many: through an association that has two columns with the same model

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 can I pass this: user_sharers should match: sharer_id? and: user_sharees should match: sharee_id? Since they are both the same user model, I'm not sure what to do.

A slightly 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 to enable additional logic, which: user_shared_posts should contain entries, where: sharer_id - user_id? and: Recommended_posts should contain messages in which: sharee_id is user_id?

Thanks in advance!

+3
source share
1 answer

:source has_many ( :class_name):

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"

User has_many:

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
+3

All Articles