AnApprentice
AnApprentice

Reputation: 110960

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?

Upvotes: 0

Views: 115

Answers (2)

Evan
Evan

Reputation: 571

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

Upvotes: 1

Ilya
Ilya

Reputation: 13487

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, e.g. 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.

Upvotes: 1

Related Questions