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"
then:
filter_name = "male"
Employee.send(filter_name) # works
However with scopes that take arguments ,
"NoMethodError (undefined method `age_range(45, 55)'
eg with this scope:
scope :age_range, ->(low, high) {where("age >= #{low} AND age <= #{high}")}
The scope works fine in the console eg
Employee.age_range(45,55)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.