首页 > 解决方案 > 如何在 MySQL 查询中调用模型方法?

问题描述

假设我的 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'}

标签: mysqlruby-on-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,
                          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

推荐阅读