Home > Enterprise >  How to where query a method defined in rails model
How to where query a method defined in rails model

Time:12-01

user.rb

scope :under_2500_value, -> { where(current_value: 0..2499) }
scope :under_5000_value, -> { where(current_value: 2500..4999) }

def current_value
  value * available.count / 100
end

available is another table that has a relationship with the user table as below.

has_many :users_availables
has_many :availables, through: :users_availables

In the rails console if I try

User.under_2500_value, it returns an error as below:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column users.current_value does not exist
LINE 1: SELECT  "users".* FROM "users" WHERE (users.curr...

Please help me find where I am going wrong

Made some edits in the question, didn’t understand the code correctly

Answer 1

scope :under_2500_value, -> { joins(:availables) { where('(value * availables.count / 100) in (?)', 0..2499) } }`


User.under_2500_value.last.current_value

The above query returns 7500 but it should have been between under 2500.

CodePudding user response:

Because current_value is an instance method, meaning it can only be called like in an instance of the User model (like User.last.current_value), but in your scope you're using it as if it were a column in the users table.

You could try calculating the value right in the query and use the IN operator with the range values;

scope :under_2500_value, -> { where('(value * available / 100) in (?)', 0..2499) }
scope :under_5000_value, -> { where('(value * available / 100) in (?)', 2500..4999) }

See the similarity between both scopes? You could make a single one;

scope :under_value, ->(value) { where('(value * available / 100) in (?)', value) }

# To be used as
# User.under_value(0..2499)

Notice that if you're using Postgres you could make the value * available / 100 calculation a generated column (see, it might translate to other RDBMS).

  • Related