开发者

Rails 3 ActiveRecord: Find model by finding it's association

class OrderItem belongs_to Item and belongs_to Order

class Item has_many OrderItems and belongs_to ItemType

class ItemType has_many Items

cl开发者_如何学运维ass Order has_many OrderItems

I would like to, within Order, find all OrderItems whose Items are of 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 building my own collection. No problem there, but I wonder if there is another way?

Thanks /j


This would be done with:

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

If you get an error about a non existing/ambiguous column, have a look at

order_items.joins(:items).to_sql

in order to find the correct column names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜