Tuesday, 3 September 2013

Rails complex joins query

Rails complex joins query

Here is my basic model heirarchy:
class Product
has_many :inventories
end
class Inventory
belongs_to :product
has_many :inventory_events
end
class InventoryEvent
belongs_to :inventory
end
InventoryEvent instances store state change + timestamps for those
changes, so inventory.inventory_events.last shows the current state.
I'm running into problems creating a query on the Product model that will
give me all the Inventories whose current state is received.
What I have right now is:
p = Product.first
p.inventories.joins(:inventory_events).where(inventory_events: {state:
'received'}).all
=> # Here I get back all Inventory that ever had the state 'received' but may
not currently be 'received'.
My SQL knowledge is pretty limited, but seems like some kind of limit to
the inventory_events: {} option might work, but haven't found a way to do
that.

No comments:

Post a Comment