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
返回与一个记录的关系,就像一个包含一个元素的数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句