내가 재고 시스템을 설계하고있어, 그것은 사용자, 제품, buy_leads, 주문 (공인 buy_leads), 입력 및 출력 있습니다.UNION이없는 인벤토리 SQL 쿼리?
class Product < ActiveRecord::Base
has_many :buy_leads
end
class BuyLead < ActiveRecord::Base
belongs_to :product
has_one :order
end
class Order < ActiveRecord::Base
belongs_to :buy_lead
belongs_to :user, :foreign_key => :authorized_by
has_many :inputs
end
class Input < ActiveRecord::Base
belongs_to :order
has_many :outputs
end
class Output < ActiveRecord::Base
# Associations
belongs_to :input
belongs_to :user
end
입력 및 출력은 양의 값을 갖는다. 출력 수량 부정함으로써 제품 재고 및 특정 제품 재고 나는,이 개 원시 SQL 쿼리에 UNION을 사용을 얻을, 다음 그룹을 함께 그들을 모두 정리해 :
그것은 작동class InventoryController < ApplicationController
def index
@inventory = Input.find_by_sql products_inventory_sql
end
def show
@inventory = Input.find_by_sql product_inventory_sql(params[:id])
end
private
def inputs_sql
"SELECT b.*, p.*, i.order_id,
i.id AS input_id,
i.quantity AS quantity
FROM inputs i
JOIN orders r ON r.id = i.order_id
JOIN buy_leads b ON b.id = r.buy_lead_id
JOIN products p ON p.id = b.product_id"
end
def outputs_sql
"SELECT b.*, p.*, i.order_id,
i.id AS input_id,
(o.quantity * -1) AS quantity
FROM outputs o
JOIN inputs i ON i.id = o.input_id
JOIN orders r ON r.id = i.order_id
JOIN buy_leads b ON b.id = r.buy_lead_id
JOIN products p ON p.id = b.product_id"
end
def products_inventory_sql
"SELECT *, SUM(quantity) AS remaining_qty
FROM (#{inputs_sql} UNION #{outputs_sql})
GROUP BY product_id"
end
def product_inventory_sql(id)
"SELECT *, SUM(quantity) AS remaining_qty
FROM (#{inputs_sql} UNION #{outputs_sql})
WHERE product_id = #{id}
GROUP BY order_id, input_id"
end
end
,
Product.inputs.by_product(id)
Product.inventory.by_product(id)
...
모든 아이디어, 또는 I H를 수행하지만 액티브에 체인 쿼리에 named_scope의 기능을 사용하고 같은 일을 할 수 있도록하고 싶습니다 보다 편리한 스키마를 바꿀 수 있습니까? 감사!
(입력 - 출력) –