Запрос 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
Я пытаюсь создать ActiveRecord эквивалент этого SQL-запроса ниже, а затем загрузить сумму столбцов *total_weight* & *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 ответ
Решение
Это должно работать:
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)