是否可以以兩種不同的方式關聯模型? (Is it possible to associate models in two different ways?)


問題描述

是否可以以兩種不同的方式關聯模型? (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

(by JZ.Bot)

參考文件

  1. Is it possible to associate models in two different ways? (CC BY‑SA 3.0/4.0)

#has-many #ActiveRecord #ruby-on-rails #has-many-through






相關問題

Ruby on Rails - Has_many,批量分配問題 (Ruby on Rails - Has_many, Mass Assignment issue)

如何在 hasMany 關聯中使用 CakePHP 2 查找? (How to use CakePHP 2 find in a hasMany association?)

模型沒有像我認為的那樣連接 (Models not connecting as I think they should be)

CakePhp find không tìm nạp hasMany mối quan hệ (CakePhp find doesn't fetch hasMany relationships)

創建關聯後,控制器中的 Ruby on rails NoMethodError (Ruby on rails NoMethodError in controller after create an association)

是否可以以兩種不同的方式關聯模型? (Is it possible to associate models in two different ways?)

在 DetailView yii2 中顯示 HAS_MANY 關係數據 (Display HAS_MANY relation data in DetailView yii2)

Rails - 檢查 has_many 關聯中是否存在記錄 (Rails - check if record exists in has_many association)

在 Rails 中,我可以在另一個模型的模型上設置 has_many 關係嗎? (In Rails, can I set a has_many relation on a model from another model?)

從大於 0 開始計數器緩存 (Starting a counter cache from greater than 0)

如何使用 has_many 關聯在 Rails 中排序? (How to sort in rails with has_many association?)

如何將 ActiveModel::Serializer :has_many 關聯的密鑰格式(即駝峰式)指定為一次性選項(不是全局配置)? (How to specify the key format (i.e. camelcase) for an ActiveModel::Serializer :has_many association as a one-off option (not global config)?)







留言討論