Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all list of scopes in ActiveRecord 3.x

I am using ActiveRecord with Rails 3.

I defined scopes in my model. How can I get the list of all scopes of that model?

Previously I could use Model.scopes

OR Can I check a scope is defined or not? Something like Model.scope_defined?("scope_name")

Thanks in advance.

like image 634
Sayuj Avatar asked Sep 27 '12 07:09

Sayuj


People also ask

What is scope in ActiveRecord?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.

What are scopes in Ruby?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is scopes how should you use it?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

How do you name a scope in Rails?

Like Ruby class methods, to invoke the named scopes, simply call it on the class object. Named scopes takes two arguments; name and lambda. Use an expressive name. Lambda is a block of code.


1 Answers

You can see if a scope is defined or not this way

Model.send(:valid_scope_name?, :scope_name)

it will return true if it does exist and nil if it does not.

If you check the source code of valid_scope_name?, you see that you can just test it using respond_to? and then avoid the logging part.

Model.respond_to?(scope_name, true)
like image 151
oldergod Avatar answered Oct 11 '22 10:10

oldergod