Ruby on Rails: Scopes

Class Book < ActiveRecord::Base
scope :published, -> { where(:published => true) }
end
# This retuns ActiveRecord::Relation object
class BooksController < ApplicationContrpller
def index
@books = Book.published
end
end
class Book < ActiveRecord::Base
scope :author_name, -> (name) { where(:authorName => name) }
end
class Book < ActiveRecord::Base
scope :available, -> (bool) { where("available = ?", bool) if bool.present? }
end
class BooksController < ApplicationContrpller
def index
# return all available & published books.
@books = Book.published.available
end
end

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CI/CD : What Is It and Why You Need It

How to communicate through BLE using Flutter

Dockerizing Strapi (v4) and CI/CD Setup with Gitlab (Part 3)

10 Must Know Terminal Commands For Mac Devs

How To Create Truffle Project

What is Azure Functions?

Stateful Data on Android with sealed classes and Kotlin Flow

Super Brief Notes on Early Source Control Systems at Microsoft

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Boula Akladyous

Boula Akladyous

More from Medium

How to learn Ruby on Rails from scratch

How to get started with Rails

Leaflet + Rails 7 quick start guide

Ruby and Ruby on Rails

Part 1: Building a Ruby on Rails API