問題描述
是否可以以兩種不同的方式關聯模型? (Is it possible to associate models in two different ways?)
I have a User model which has many Committees a Committee also belongs to a user.
Because users are a mixture of Admins and regular web users, I've developed a new concept, where a User can favorite a Committee.
Is it possible to associate the User and Committee models in a second way?
Where a user:
has_many :favorites
has_many :committees, through: :favorites
Obviously this will collide with the above User.first.committees but is there a way I could use another noun but still keep the basic through logic?
This would be awesome if possible.
參考解法
方法 1:
Yes you can have two associations to the same model. Something like this.
has_many :committees
has_many :favorites
has_many :favorite_committees, through: :favorites
Thus you will have three models User, Committee and Favorite.
You can also refer this.
http://guides.rubyonrails.org/association_basics.html