mysql - 如何在 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'}
解决方案
我建议你应该避免这样做。相反,您可以通过在查询本身中添加两个字段值来使上述查询工作。
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
推荐阅读
- reactjs - 我/应该如何拆分我的反应集成测试?
- python - 创建循环以填充数据框时获取 KeyError
- javascript - 访问导出变量的更改值
- javascript - 如何阅读[object Object]?
- c++ - 使用 winrt::com_ptr
使用 D3D11CreateDevice()? - google-cloud-platform - 如何保存谷歌云对象跟踪视频?
- transactions - SAGA 代表什么?
- python-3.x - 为什么默认字段 id 的 'read_only' 为 True?
- python - Matplotlib 底图多形状动画异常:“list”对象没有属性“set_animated”
- sql - 拆分 FullName 哪里有空值(db2 sql)