【问题标题】:How to call a model method inside MySQL query?如何在 MySQL 查询中调用模型方法?
【发布时间】:2019-06-27 09:10:05
【问题描述】:

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

【问题讨论】:

  • 你不应该那样做

标签: mysql ruby-on-rails


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 2022-11-02
    • 1970-01-01
    • 2016-06-21
    • 2016-02-17
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多