Model scopes in ruby on rails. Add custom query using scopes in ruby on rails

Total Blog Views: 49

Blog Status: publish

Created By: swazahmad Created at: 07-11-2021

Tags:

What is scope?

Scopes are custom queries written in the model used for retrieving and querying objects.

How to use scope in ruby on rails?

scope takes name and lambda

scope :admin, → {where(is_admin: true)}

How to call this scope

User.admin

How to call scope with argument

scope :created between, -> (from, to) {
where(
"created_at > ? AND created_at < ?", from, to
)}
Invoice.created between(test, today)

What is Default Scope.


A default scope gets automatically applied whenever you access the model. Be careful when this is used.

default_scope { where(active: true }
# returns only active users User.all

What is Unscoped in ruby on rails?.

If you want to remove all the previously applied scopes from the model, use unscoped.

scope :active, → {where(active: true)}
# returns all users User.active.unscoped

Advantages of scopes in ruby on rails.

Scope will always return Activerecord::Relation object.

  1. This helps in method chaining.
  2. It is a great way to keep the model DRY.
  3. Scope looks cleaner.
  4. Make application faster


swazahmad

Swaz is Practice Lead of ROR Developer. he's a Blogger, Mentor, and Rubyst. He has expertise in Javascript also . he's highly skilled in designing, developing and testing web applications. He enjoys being challenged and interesting with projects that need him to



Comments



  • swazahmad | almost 4 years ago
    Awesome Information Thanks For Sharing
Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads