如何在MySQL查询中调用模型方法?

如何在MySQL查询中调用模型方法?,mysql,ruby-on-rails,Mysql,Ruby On Rails,假设我在Rails方法中有这样一个实例变量(稍后我将使用) 我想在这个查询中实现一个模型方法,如下所示 User < ApplicationRecord def sum_all self.first_price + self.tax end end 我建议你应该避免那样做。相反,您可以通过在查询本身中添加两个字段值来实现上述查询 def index @users = User.select("users.id as usr_id,

假设我在Rails方法中有这样一个实例变量(稍后我将使用)

我想在这个查询中实现一个模型方法,如下所示

User < ApplicationRecord
  def sum_all
    self.first_price + self.tax
  end
end

我建议你应该避免那样做。相反,您可以通过在查询本身中添加两个字段值来实现上述查询

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

你不应该那样做
{"status":500,"error":"Internal Server Error","exception":"#\u003cActionView::Template::Error: Mysql2::Error: Unknown column 'users.sum_all' in 'field list'}
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