David David - 1 year ago 60
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.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download