Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

class 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

like image 252
J. Martin Avatar asked May 03 '11 12:05

J. Martin


1 Answers

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.

like image 170
moritz Avatar answered Sep 23 '22 06:09

moritz