Daniel Bonnell
Daniel Bonnell

Reputation: 4997

ActiveRecord: Reference attribute from associated model in where statement

I've got two models with a has_many / has_many relationship. I have a variable exp_ids which is an array of integers representing the id's of some ExperienceLevel records. I need to write a query that will select all JobDescriptions that have an ExperienceLevel with one of those ids.

The query must work on an existing ActiveRelation object called job_descriptions, which is being passed through some flow controls in my controller to filter the results based on my params.

I've tried these queries below and some other variations, but with little success. As far as I can tell, ActiveRecord thinks that experience_levels is an attribute, which is causing it to fail.

Here are my models:

class JobDescription < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :experience_levels, through: :job_description_experience_levels
end

class JobDescriptionExperienceLevel < ActiveRecord::Base
    belongs_to :job_description
    belongs_to :experience_level
end

class ExperienceLevel < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :job_descriptions, through: :job_description_experience_levels
end

I'm not sure if what I want to do is even possible. I've used a similar approach for another job_description filter where I selected the company_id, but in the case, company_id was an attribute of JobDescription.

Upvotes: 2

Views: 1410

Answers (3)

Fred Willmore
Fred Willmore

Reputation: 4604

job_descriptions.joins(:experience_levels).where(experience_levels: {id: exp_ids})

Upvotes: 1

Carpela
Carpela

Reputation: 2195

Try this one. Note the lack of plural on the experience level.id

job_descriptions.includes(:experience_levels).where("experience_level.id = ?", exp_ids).references(:experience_levels)

Upvotes: 0

vegetaras
vegetaras

Reputation: 119

Try this:

job_descriptions.joins(:job_description_experience_levels).where(job_description_experience_levels: { experience_level_id: exp_ids })

Upvotes: 2

Related Questions