首页 > 解决方案 > 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. 有没有不同的方式来问这个问题?

标签: ruby-on-rails

解决方案


我猜你想做一些事情,比如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') }

推荐阅读