Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 998
Aeradriel Avatar asked Jun 22 '26 18:06

Aeradriel


1 Answers

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

like image 77
Shalev Shalit Avatar answered Jun 25 '26 19:06

Shalev Shalit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!