David David - 5 months ago 20
Ruby Question

Programmatically apply an ActiveRecord scope that accepts arguments

I'm building a system where it is necessary to programmatically apply one or more where clauses to an ActiveRecord Relation object. This works great in the following situation:

Assume the Employee model has scope called "male"


filter_name = "male"
Employee.send(filter_name) # works

However with scopes that take arguments,

"NoMethodError (undefined method `age_range(45, 55)'

e.g. with this scope:

scope :age_range, ->(low, high) {where("age >= #{low} AND age <= #{high}")}

The scope works fine in the console e.g.


Thanks for any advice.


Object#send accepts the name of the method and its arguments:

name = :age_range
low  = 45
high = 55
Employee.send(name, low, high)

I would recommend to use Object#public_send, to make sure you only use publicly accessible API:

Employee.public_send(name, low, high)