Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Is it possible to check if a named scope is valid for a given active record?

I'm Using Ruby 1.8.7-p374 and Rails 2.3.18. (Yeah, I know, we're working on it.)

I'm considering dynamically passing a named scope to be used as a condition for an ActiveRecord. Is it possible to check to see if a passed string is a valid named scope for the record?

For Example:

If I have a named scope called :red defined for Car

named_scope :red, :condition => ["color = ?", "red"]

Then is there some function where I could do

Car.some_function("red")   # returns true
Car.some_function("blue")  # returns false
like image 649
warder57 Avatar asked Dec 13 '25 00:12

warder57


1 Answers

You can use .respond_to?(:method) (documentation here)

In your case :

Car.respond_to?(:red)  # => true
Car.respond_to?(:blue) # => false

But you said:

I'm considering dynamically passing a named scope to be used as a condition for an ActiveRecord

I hope you will not use something like this:

# url
/cars?filter=red

# controller
def index
 @cars = Car.send(params[:filter]) if params[:filter].present? && Car.respond_to?(params[:filter])
 @cars ||= Car.find(:all)

Guess what woud happen if I use this URL?

/cars?filter=destroy_all

The Car model responds to the method .destroy_all, so Ruby calls it on the Car model. BOOM, all cars are destroyed!

like image 173
MrYoshiji Avatar answered Dec 15 '25 12:12

MrYoshiji



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!