1

I'm Using Rails 3.2 and i wish to know a " rails way " to create an object based on parameters coming from another. I have the class StoredItem and the class RequestedItem, they are not related, but during the process to attend the requested item i wish to list all itens and qty stored from a requested part number. I thought something like

@requested_items = RequestedItem.includes(:item_description).where("item_request_id = ?", params[:id])

@stored_items = StoredItem.where("item_description_id = ?",@requested_items.item_description_id)

Obviously this seems don't work because i have a lot of descriptions id to compare, not only one, so, whats the best and correct way to make it work?

Any help will be appreciated, thank you :)

1 Answer 1

3
@stored_items = StoredItem.where("item_description_id IN (?)",@requested_items.map(&:item_description_id))

Or

@stored_items = StoredItem.where(:item_description_id => @requested_items.map(&:item_description_id))
Sign up to request clarification or add additional context in comments.

3 Comments

The second option is much better (no pure SQL written which lets Rails deal with the SQL generation, following the DB Adapter). Also, @requested_items.pluck(:item_description_id) would be a little more efficient than a .map(&:item_description_id)
Good point, but depends if he's using requested items elsewhere
Great, i used the second option, it solved my question. Thanks Baloo and MrYoshiji ;)

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.