Stefan Dunn
Stefan Dunn

Reputation: 5513

Ruby on Rails: Select from database where column equals a value from array

If I have an array of IDs from a table (table1) in my database. Is there a way of querying another table (table2) to select all the records where a column equals a value equal to one of the IDs from table1.

My code so far is:

LabQuestion.where("product_id=#{Product.where(:brand_id => brand_id).pluck(:id)}")

In this code, I am trying to retrieve all the Lab Questions which are linked to all the products from a brand. This code does not work, but I've tried to demonstrate my needs.

Upvotes: 2

Views: 1404

Answers (2)

Suman Ranjan Panda
Suman Ranjan Panda

Reputation: 144

You can use includes instead of joins as below

LabQuestion.includes(:product).where(:products => { :brand_id => brand_id })

Upvotes: 1

Mischa
Mischa

Reputation: 43318

Assuming you have setup your relations properly, you can use joins to join the two tables and query them like this:

LabQuestion.joins(:product).where(:products => { :brand_id => brand_id })

Upvotes: 1

Related Questions