0

Here is the rails 3 query in the app:

Order.where('id IN (?)',ContractItem.where(contract_id: @contract.id).select('contract_item_id'))

Here is the only record in contract_item table:

enter image description here

As shown in the record, the @contract.id is equal to 1 and we expect ContractItem.where(contract_id: @contract.id).select('contract_item_id') returns array [2]. So Order.where('id IN (?)',ContractItem.where(contract_id: @contract.id).select('contract_item_id'))should return order#2. However what we have got is nothing. We figure an empty array must be returned instead. Is there something wrong with the code above?

0

1 Answer 1

2

You're getting back an array, but it's an array of ContractItem objects with a single column, not an array of numbers.

Try instead...

Order.where('id IN (?)',ContractItem.where(contract_id: @contract.id).pluck(:contract_item_id))
Sign up to request clarification or add additional context in comments.

3 Comments

Or use pluck method, ContractItem.where(contract_id: @contract.id).pluck(:contract_item_id)
Yes, @Iceman good point! Don't need to return the whole record. I'll modify my answer.
Here is an article about pluck and select. rubyinrails.com/2014/06/rails-pluck-vs-select-map-collect

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.