Rails 3 ActiveRecord: search for a model by finding its association

class OrderItem belongs_to Item and belongs_to Order class Item has_many OrderItems and belongs_to ItemType class ItemType has_many Items class Order has_many OrderItems 

I would like to find all OrderItems within the order whose elements are of the type ItemType

 def get_by_item_type(id) order_items.where(:item => {:item_type_id => 3}) 

Obviously, I can do this by finding all OrderItems, looping, testing, and creating my own collection. No problem, but I wonder if there is another way?

Thanks / J

+6
source share
1 answer

This will be done using

 def get_by_item_type(id) order_items.joins(:item).where(:item_type_id => id) end 

If you receive an error message with a non-existent / ambiguous column, see

 order_items.joins(:items).to_sql 

to find the correct column names.

+4
source

Source: https://habr.com/ru/post/887187/


All Articles