Reputation: 5905
I've created a many to many relation ship like the following structure.
Class User
has_many :companies, :through => company_admins
has_many :company_admins
end
Class Company
has_many :company_admins
has_many :users, :through => company_admins
end
Class CompanyAdmin
belongs_to :company
belongs_to :user
end
Here, User
can be assigned as admin on many Company
.
Now I've to create another many-to-many relationship with User
and Company
, where User
can follow many company
. How can I do that?
I've added
Class User
has_many :companies, :through => company_admins
has_many :companies, :through => followers
has_many :company_admins
has_many :followers
end
Class Company
has_many :company_admins
has_many :followers
has_many :users, :through => company_admins
has_many :users, :through => followers
end
Class Follower
belongs_to :company
belongs_to :user
end
Now, If I search for users which are admin to any company using @company.users
it searches in the Follower
table.
Can anyone help me with the association?
Upvotes: 0
Views: 352
Reputation: 33552
I guess your association set up should be something like this
#user.rb
Class User
has_many :company_admins
has_many :companies, :through => company_admins
has_many :followers
has_many :followed_companies, :through => followers, :source => :company
end
#company.rb
Class Company
has_many :company_admins
has_many :users, :through => company_admins
has_many :followers
has_many :followed_users, :through => followers, :source => :user
end
#follower.rb
Class Follower
belongs_to :company
belongs_to :user
end
Now if you give @company.users
, it will search in company_admins
table and if you give @company.followed_users
, it will search in followers
table.
Note: Didn't tested.
Upvotes: 1