2

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.

2 Answers 2

1

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 })
Sign up to request clarification or add additional context in comments.

Comments

1

You can use includes instead of joins as below

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

1 Comment

You can use includes, but it's not recommended in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.