Jeremy Thomas
Jeremy Thomas

Reputation: 6694

Rails 5: Using a model function in a scope

I am trying to use a model function within a scope and was wondering if something like this is possible?

class WeighIn < ApplicationRecord
    belongs_to :client

    scope :overweight, -> { where("current_weight >= ?", target_weight) }

    def target_weight
        client.target_weight
    end
end

When I call WeighIn.overweight I see the error:

undefined local variable or method `target_weight' for #<WeighIn::ActiveRecord_Relation:0x007fb31baa1fb0>

... which makes sense since the client_id is changing depending on the weigh_in. Is there a different way to ask this question?

Upvotes: 0

Views: 41

Answers (2)

arieljuod
arieljuod

Reputation: 15848

I'm guessing you want to do something like weigh_in.overweight to get all WeighIn with weight greated than weigh_in.target_weight. You can't do that the way you want, since a scope is basically a Class method and target_weight is an instance method.

What you can do is to add an argument to the scope:

scope :overweight, ->(weight) { where("current_weight >= ?", weight) }

Then add an instance method

def overweight
  WeighIn.overweight(target_weight)
end

and now weigh_in.overweight returns what you want.

EDIT: if you want to get all overwight weigh_in related to its user the you have to join the tables like @Michelson's answer, something like:

scpoe :overweight, -> { joins(:clients).where('current_weight >= clients.target_weight') }

Upvotes: 3

Michelson
Michelson

Reputation: 351

maybe something like this would work

scope :overweight, -> { joins("clients").where("current_weight >= clients.current_weight") }

Upvotes: 0

Related Questions