Rails Active Record 对 select 语句进行算术计算

Rails Active Record to make arithmetic calculation over a select statement

我正在尝试从现有 table 列计算值并将其用于外部变量。

让我的 table 列为:["id","unit_price","quantity","extras_1","extras_2"] 我正在使用 sql 命令作为参考在 rails 中展示我想做的事情。

SQL 命令:

SELECT unit_price*quantity AS "regular_price", 
       unit_price*quantity-unit_price*quantity*discount AS "price_after_discount"
FROM order_details;

在 Rails Active Record 查询中,我尝试了同样的操作:

OrderDetail.select('unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount')

从上面 query.i 尝试基于派生的排序 attributes.it 有效 perfectly.But 我无法通过查询看到派生的属性值。

我得到的输出没有派生属性:

[#<OrderDetail >,#<OrderDetail >]

但我需要输出为:

[#<OrderDetail regular_price: 43, price_after_discount: 54>,#<OrderDetail regular_price: 54, price_after_discount: 76>]

我尝试了下面的查询来排序 data.It 完美地排序了数据:

OrderDetail.select('unit_price,quantity,unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount').order('regular_price desc')

我可以使用以下命令访问这些值:

OrderDetail.select('unit_price,quantity,unit_price*quantity AS extras_1,unit_price*quantity-unit_price*quantity*discount AS extras_2')

以上命令有效,因为 extras_1extras_2 是 table 列。

但是当分配给现有 table column.I 需要派生属性是不存在的 table 列名称时它是有效的。

我如何从 record.I 访问派生的属性值可以通过将它们分配给现有的 table column.But 来访问它们table 列。

您将看不到派生(别名)属性。但是他们在场。

OrderDetail.select('unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount').first.regular_price

将打印 regular_price.

您在 rails 控制台中看到的是 inspect 方法的输出。 inspect 方法未实现以显示别名属性。因此产生了混乱。

浏览此文档:http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/select

If an alias was specified, it will be accessible from the resulting objects:

Model.select('field AS field_one').first.field_one
#=> "value"

您的属性完全可以访问。打电话给他们! :)

作为附加说明,我建议您使用更现代的方式来编写查询:

class OrderDetail
  scope :with_calculated_prices, -> do
    regular_price = (arel_table[:unit_price] * arel_table[:quantity])
    price_after_discount = (regular_price - regular_price * arel_table[:discount])
    select(regular_price.as('regular_price'), price_after_discount.as('price_after_discount'))}
end

price_after_discount 最好定义为

price_after_discount = (regular_price * (1 - arel_table[:discount]))