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

--

--

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