Aeradriel
Aeradriel

Reputation: 1232

ActiveRecord 'where' clause using function

I am trying to apply filters on an ActiveRecord::Relation. I would like to apply a 'where' clause (or the equivalent) to make the following call.

record = Record.all
record.where(record.remaing_units > 5)

I know this would be easy to get coding a fonction and passing it 2 arguments but I would like to know if there is a cleaner way to do it, more 'where' like.

EDIT : remaining_units is a method of Record class calculating subtraction between 2 fields.

Upvotes: 3

Views: 2738

Answers (2)

Shalev Shalit
Shalev Shalit

Reputation: 1963

You cannot use methods as mysql query.

You can run the same function as sql method:

Record.where('a + b > 5')

Or get all records from the db and use ruby select method:

Record.all.select{ |r| r. remaing_units > 5 }

** you can try Squeel gem for better query

Upvotes: 5

ilan berci
ilan berci

Reputation: 3881

class Record < ActiveRecord::Base
  scope :remaining_space, ->(n) {
    where("records.field_1 - records.field_2 > ?", n)
  }
end

Record.remaining_space(5)

Upvotes: 1

Related Questions