假设我在Rails方法中有一个这样的实例变量(稍后将使用)
def index
@users = User.select("users.id as usr_id,
users.name as user_name,
users.first_price as price,
users.tax as tax,
(#here's model method)=> users.sum_all as grand_total")
.where("users.deleted_at is null AND
users.id IN (?)
@users.pluck(:id))
.order(@order_by)
end
并且我想在此查询中实现一个看起来像这样的模型方法
User < ApplicationRecord
def sum_all
self.first_price + self.tax
end
end
如果按上述方法放置此方法,则会出现错误
{"status":500,"error":"Internal Server Error","exception":"#\u003cActionView::Template::Error: Mysql2::Error: Unknown column 'users.sum_all' in 'field list'}
答案 0 :(得分:1)
我建议您避免这样做。相反,您可以通过在查询本身中添加两个字段值来使上面的查询起作用。
def index
@users = User.select("users.id as usr_id,
users.name as user_name,
users.first_price as price,
users.tax as tax,
users.first_price + users.tax as grand_total")
.where("users.deleted_at is null AND users.id IN (?)", @users.pluck(:id))
.order(@order_by)
end