[英]Ruby: specify has_many :through association when several has_many :through associations are given
我有一個簡單的數據設置,其中包含用於用戶的模型和用於任務的模型。 在這兩個模型之間,我有兩個has_many:through關聯:獎學金和工作分配。 總的來說,我想為一個任務指定幾個關注者和幾個受讓人。
現在,我想顯示特定任務的所有受讓人和所有關注者。 如果只有一個關聯,我可以簡單地執行@ task.users。 由於我有兩個關聯,因此我想指定要獲得所有用戶的關聯。
看我的代碼:
class User < ActiveRecord::Base
has_many :assignments
has_many :tasks, through: :assignments
has_many :fellowships
has_many :tasks, through: :fellowships
end
class Task < ActiveRecord::Base
has_many :assignments
has_many :users, through: :assignments
has_many :fellowships
has_many :users, through: :fellowships
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :task
end
class Fellowship < ActiveRecord::Base
belongs_to :user
belongs_to :task
end
假設我有一個任務
@task = Task.first
我現在想讓所有受讓人和所有追隨者都喜歡
@assignees = @ task.users“超過關聯分配”
@followers = @ task.users“超過關聯關注度”
但我不知道該怎么做。
謝謝您的幫助!
您可以按照以下方式編寫。
has_many:assignment_tasks,通過::assignments,source::task
has_many:fellowship_tasks,通過::fellowships,來源:: task
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.