Is there any difference between scope and named_scope?
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.
scope in active record is like class methods but they return Relation object which means you can call another scope or active record querying method on it. Show activity on this post. The best way to understand about the details is to go to API Documentation.
With default scopes, we can change/specify how records are retrieved by default from Active Record database. Any subsequent queries to the database will be retrieved/rendered following the default scope definition. For example, call the select Active Record finder method on the Tea class where rating is not exactly 3.
Simply put, a scope is just a custom chain of active record methods. They are sets of pre-defined queries that can be chained to build other complex Queries. Scopes help you D.R.Y out your active record calls and also keep your codes organized. Scopes make it easy to find the records you need at a particular time.
scope
is used in Rails 3 >, named_scope
was used in previous versions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With