0

how to call a active record named scope with a string and Access named scope dynamically have information on how to choose a scope based on a string or symbol, if you're willing to use send or public_send. I'm rather concerned by the security implications of using those methods, however.

How can I choose a named scope without using send or public_send?

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338

1 Answers1

1

Since named_scopes are normal methods, AFAIK, there is no other way of calling a method dynamically by the name string/symbol in ruby.

However since your concern is about the security, there are two options.

1 - Have a private method to dispatch the actual string method name

This will give your code to control the method name , instead of trusting an outside string. Something like..

#Ex: if your method name is 'all', and user sends the string 'All' 

User.send(scope_method('All'))   

private
def scope_method(name)
  {'All' : 'all'}
end

2 - Have a case statement

Depending on the user string, but this could get really ugly really quickly

sameera207
  • 16,547
  • 19
  • 87
  • 152