日曜日 :
私はARELを使用してMySQLケース文で書かれたActiveRecordのコードをクリーンアップしようとしています。私はARELはcase文を処理することができます知っているが、確かではない、それを使用する方法。
私は、数量とUSER_ID(外部キー)列を持つOrdersテーブルを持っているので。注文数量に基づいて異なる価格体系があるように私は動的に注文の価格を計算しています。これは、ARコードは次のようになります。
def orders_with_price
<<-SQL
orders.*,
SUM(CASE orders.quantity
WHEN 2 THEN 500 * orders.quantity
WHEN 5 THEN 450 * orders.quantity
WHEN 10 THEN 350 * orders.quantity
END) AS total_price
SQL
end
Order.
select(orders_with_price).
group("orders.user_id").
having("total_price > ?", minimum_price).
order("total_price")
アディ:
私はARELのv7.xよりは、導入から考えるAREL ::ノード::ケース case文のために使用することができます。あなたは、このクエリを再作成することができます:
def case_statements
orders = Order.arel_table
Arel::Nodes::Case.
new(orders[:quantity]).
when(2).then(orders[:quantity] * 500).
when(5).then(orders[:quantity] * 450).
when(10).then(orders[:quantity] * 350)
end
Order.
select(Arel.star).
select(Arel::Nodes::Sum.new(case_statements).as("total_price")).
order("total_price")