ruby-on-rails - Rails 5:在范围内使用模型函数
问题描述
我正在尝试在范围内使用模型函数,并且想知道这样的事情是否可能?
class WeighIn < ApplicationRecord
belongs_to :client
scope :overweight, -> { where("current_weight >= ?", target_weight) }
def target_weight
client.target_weight
end
end
当我打电话时,WeighIn.overweight
我看到了错误:
undefined local variable or method `target_weight' for #<WeighIn::ActiveRecord_Relation:0x007fb31baa1fb0>
client_id
...这是有道理的,因为weigh_in
. 有没有不同的方式来问这个问题?
解决方案
我猜你想做一些事情,比如weigh_in.overweight
让所有WeighIn
体重都超过weigh_in.target_weight
. 你不能按照你想要的方式去做,因为作用域基本上是一个类方法并且target_weight
是一个实例方法。
您可以做的是向范围添加一个参数:
scope :overweight, ->(weight) { where("current_weight >= ?", weight) }
然后添加一个实例方法
def overweight
WeighIn.overweight(target_weight)
end
现在weigh_in.overweight
返回你想要的。
编辑:如果你想获得与其用户相关的所有超重 weight_in,你必须加入像@Michelson's answer这样的表格,比如:
scpoe :overweight, -> { joins(:clients).where('current_weight >= clients.target_weight') }
推荐阅读
- pandas - 使用 np.where 时,pandas dropna 不会删除 nan
- wso2 - 在 WSO2 API Manager 2.1 上导入 Swagger JSON 时出错
- python - python中的二进制搜索,输出检查的值
- oracle - ORA-12514 TNS:listener 目前不知道 oracle 11g 中连接描述符中请求的服务
- android - 单击按钮后,Recyclerview 适配器中的项目会跳转到右侧
- html - 如何在不使用背景图像的情况下获得背景磨砂玻璃效果
- javascript - 如何在Javascript中获取元素及其子元素的所有计算css属性
- c# - 从二进制 .resources 文件中提取图标
- android - 根据条件显示对话框或活动
- java - 在struts 2中管理会话(HTTP Session)的麻烦