简体   繁体   中英

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:

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):

JobTitle.find_by(id: 6).users

It's just how has_many works: one model has many other models. Where returns a relation, eg JobTitle.where('id > ?', 1) will return a collection of records. In your case where returns a relation with one record, like an array with one element.

The codes JobTitle.where(id: 6) return a collection of records, The best way is use the find method.

Just try this:

 JobTitle.find(6).users

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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