![](/img/trans.png)
[英]Active Record Associations: has_and_belongs_to_many, has_many :through or polymorphic association?
[英]Active Record Associations - Error w has_many :through Association?
class User < ApplicationRecord
has_many :user_positions
has_many :job_titles, through: :user_positions
class JobTitle < ApplicationRecord
has_many :user_positions
has_many :users, through: :user_positions
class UserPosition < ApplicationRecord
belongs_to :user
belongs_to :job_title
給定以上模型ActiveRecord關聯,我試圖查詢JobTitle,然后像這樣返回所有具有該JobTitle的用戶:
JobTitle.where(id: 6).users
這是錯誤的:
undefined method `users' for #<JobTitle::ActiveRecord_Relation
我究竟做錯了什么?
使用find_by
的find
( find
引發RecordNotFound
如果沒有與此ID的記錄):
JobTitle.find_by(id: 6).users
這就是has_many
工作方式:一個模型具有許多其他模型。 Where
返回一個關系,例如JobTitle.where('id > ?', 1)
將返回記錄的集合。 在您的情況下where
返回一條記錄的關系,例如具有一個元素的數組。
代碼JobTitle.where(id:6)返回記錄的集合,最好的方法是使用find方法。
嘗試一下:
JobTitle.find(6).users
要么
JobTitle.where(id: 6).first.users
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.