简体   繁体   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

Given the above model ActiveRecord associations, I'm trying to query for a JobTitle and then return all users with that JobTitle like so: 给定以上模型ActiveRecord关联,我试图查询JobTitle,然后像这样返回所有具有该JobTitle的用户:

JobTitle.where(id: 6).users

This is erroring with: 这是错误的:

undefined method `users' for #<JobTitle::ActiveRecord_Relation

What am I doing wrong? 我究竟做错了什么?

Use find_by of find ( find raises RecordNotFound if there is no record with this id): 使用find_byfindfind引发RecordNotFound如果没有与此ID的记录):

JobTitle.find_by(id: 6).users

It's just how has_many works: one model has many other models. 这就是has_many工作方式:一个模型具有许多其他模型。 Where returns a relation, eg JobTitle.where('id > ?', 1) will return a collection of records. Where返回一个关系,例如JobTitle.where('id > ?', 1)将返回记录的集合。 In your case where returns a relation with one record, like an array with one element. 在您的情况下where返回一条记录的关系,例如具有一个元素的数组。

The codes JobTitle.where(id: 6) return a collection of records, The best way is use the find method. 代码JobTitle.where(id:6)返回记录的集合,最好的方法是使用find方法。

Just try this: 尝试一下:

 JobTitle.find(6).users

Or 要么

JobTitle.where(id: 6).first.users

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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