Reputation: 2883
I have a job which has_many
categories
I have a business which has_many
categories.
Currently I'm only assigning 1 category to both job and a business but this will change later which is why I've created the has_many association.
The categories assigned to businesses and jobs are from the same category table selected with a select menu with the intention of matching them.
If have a job, how can I find businesses that match the jobs category.
For example
job = Job.find(1)
> job.categories.first.name
=> "programmer"
If I want to find all Businesses listed that have the programmer
category how can I do this?
I think I might need a join or include similar to this but I'm not sure how this should be written exactly.
Business.includes(:categories).where(:categories == ...)
Upvotes: 0
Views: 40
Reputation: 5294
Your code is almost right. This should work:
Business.joins(:categories).where(categories: {name: 'programmer'})
Or if you have multiple categories:
Business.joins(:categories).where(categories: {name: ['programmer', 'other']})
Upvotes: 1