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 中找到其 Items 类型为 ItemType 的所有 OrderItems
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
为了找到正确的列名。
关于ruby-on-rails - Rails 3 ActiveRecord : Find model by finding it's association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5869252/