2011-05-03 58 views
6
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 
查找模型

我想,秩序中,找到其中的項目是類型的ItemTypeRails 3中ActiveRecord的:通過查找它的關聯

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

很顯然,我可以找到所有的OrderItems做到這一切的OrderItems,循環,測試和構建我自己的集合。那裏沒問題,但我想知道是否有另一種方法?

感謝 /J

回答

4

這與做:

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

如果你得到一個關於一個不存在/不明確的列的錯誤,在看看

order_items.joins(:items).to_sql 

爲了找到正確的列名稱。

+0

謝謝,我會盡快嘗試,因爲它看起來是正確的...謝謝 – 2011-05-28 20:05:03

+0

終於實現了這個系統的一部分,像一個魅力工作。 – 2011-06-10 15:24:31