RocketGuy3
RocketGuy3

Reputation: 625

How can I get all the records in a table where any value of an associated table is in a given array?

I think if I had a better idea how to word this question, I would have been able to find an answer already... Anyways, I have a table called Vendors that has a many-to-many relationship with a table called Basins. I would like to be able to retrieve all the vendors that have at least one basin in an array of basins that is passed in as input.

So if I had three vendors like:

vendor1.basins = [Basin.first, Basin.second]
vendor2.basins = [Basin.second, Basin.third]
vendor3.basins = [Basin.third, Basin.fourth]

And I wanted to get all the vendors containing anything from [Basin.first, Basin.fourth], I would get both vendor1 and vendor3. If the array was [Basin.first, Basin.second], I would get both vendor1 and vendor2. I thought select might be the way to go here, but everything I've tried has been flagrantly wrong.

Thanks in advance.

Upvotes: 0

Views: 41

Answers (2)

nonameg
nonameg

Reputation: 136

You can add scope to Vendor model:

scope :foo, ->(basins_arr){ joins(:basins).
   where(basins: { id: basins_arr.collect(&:id)})

Upvotes: 0

Kuldeep
Kuldeep

Reputation: 884

I am assuming you are using Rails >= v4.0.0.

You can get vendors like:

Vendor.joins(:basins).where(basins: { id: [Basin.first.id, Basin.fourth.id] })

I hope this will help you.

Upvotes: 1

Related Questions