Rails复杂连接查询

时间:2013-09-04 00:12:26

标签: sql ruby-on-rails

这是我的基本模型heirarchy:

class Product
  has_many :inventories
end
class Inventory
  belongs_to :product
  has_many :inventory_events
end
class InventoryEvent
  belongs_to :inventory
end

InventoryEvent实例存储这些更改的状态更改+时间戳,因此inventory.inventory_events.last显示当前状态。

我遇到了在Product模型上创建查询的问题,该模型将为我提供当前状态为received的所有库存。

我现在拥有的是:

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'.

我的SQL知识非常有限,但似乎inventory_events: {}选项的某种限制可能有效,但还没有找到办法。


编辑:这是我目前的解决方法,只是为了展示我的最终目标。希望有一种方法可以为这样的查询建模。

class Inventory
  def self.received_items
    includes(:inventory_events).select {|i| i.current_state == 'received'}
  end
  def current_state
    inventory_events.last.state
  end
end

Product.first.inventories.received_items
=> # Here I get the correct array of inventories

2 个答案:

答案 0 :(得分:0)

您可以通过使用范围和合并方法来实现此目的。范围将允许您保持模块的where条件。合并方法将允许您选择具有已收到的InventoryEvent的库存。

# call this to get the inventories for the product that have been recieved
product.inventories.received

class InventoryEvent
  def self.received
    where("state = ?", "received")
  end

  def self.most_recent
    order("inventory_events.created_at desc").first
  end
end

class Inventory
  def self.received
    joins(:inventory_events).
    merge(InventoryEvent.received).
    merge(InventoryEvent.most_recent)
  end
end

答案 1 :(得分:0)

我发现了这一点SQL并且它一直在为我工作:

joins(:inventory_events).where("inventory_events.id IN (SELECT MAX(id) FROM inventory_events GROUP BY inventory_id) AND state = 'received'")