具有嵌套模型和派生列值的ActiveRecord查询?

时间:2012-07-01 02:56:40

标签: ruby-on-rails-3 activerecord

我有以下关系:

class Order < ActiveRecord::Base
  has_many :item_selections, :dependent => :destroy
  has_many :inventory_items, :through => :item_selections
end
class InventoryItem < ActiveRecord::Base
  has_many :item_selections, :dependent => :destroy
  has_many :orders, :through => :item_selections
end
class ItemSelection < ActiveRecord::Base
  belongs_to :order
  belongs_to :inventory_item
end

我正在尝试在下面创建此SQL查询的ActiveRecord等效项,然后加载* total_weight *&amp;的总和。 * total_volume *列到实例变量中:

select t1.quantity, t2.volume, t2.weight, 
t2.volume * t1.quantity as total_volume,    
t1.quantity * t2.weight as total_weight
from orders t0
inner join item_selections t1 on t0.id = t1.order_id
inner join inventory_items t2 on t1.inventory_item_id = t2.id
where t0.id = <id_val>     

有关使用ActiveRecord获取这些值的正确方法的想法吗?

1 个答案:

答案 0 :(得分:0)

这应该有效:

orders = Order.select('orders.*, t1.quantity, t2.volume, t2.weight, t2.volume * t1.quantity as total_volume, t1.quantity * t2.weight as total_weight').joins('inner join item_selections t1 on orders.id = t1.order_id, inner join inventory_items t2 on t1.inventory_item_id = t2.id').where(:id => id_val)

使用这样的自定义选择会添加选定的其他内容作为返回对象的属性,因此您可以引用它们,就像它们是订单对象的字段一样:

@total_volume_sum = orders.sum(:total_volume)
@total_weight_sum = orders.sum(:total_weight)