J. *_*tin 6 activerecord ruby-on-rails associations
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
我想在Order中查找其Item属于ItemType类型的所有OrderItem
def get_by_item_type(id)
  order_items.where(:item => {:item_type_id => 3})
显然,我可以通过查找所有OrderItems,循环,测试和构建我自己的集合来做到这一点.没问题,但我想知道是否有另一种方式?
谢谢/ j
这可以通过以下方式完成:
def get_by_item_type(id)
  order_items.joins(:item).where(:item_type_id => id)
end
如果您收到有关不存在/不明确列的错误,请查看
order_items.joins(:items).to_sql
为了找到正确的列名称。