繁体   English   中英

活动记录关联-错误w has_many:通过关联?

[英]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_byfindfind引发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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM