Chapter 9 - Advanced Active Record Flashcards
ORM
Object-relational mapping framework
Scopes
Scopes (or “named scopes” if you’re old school) allow you to define and chain query criteria in a declarative and reusable manner.
scope :submitted, -> { where( submitted: true) }
scope :underutilized, -> { where(‘ total_hours > User.submitted
Scope class method
def self.delinquent where(' timesheets_updated_at
Scope parameters
scope :newer_than, ->( date) { where(‘ start_date > ?’, date) }
BillableWeek.newer_than( Date.today)
Chaining scopes
scope :submitted, -> { where( submitted: true) }
scope :underutilized, -> { submitted.where(‘ total_hours
default_scope
we can use a default scope to simplify our general queries.
default_scope { where( status: “open”) }
> > Timesheet.pluck(: status)
= > [” open”, “open”, “open”]
Arel
Arel is a SQL AST manager for Ruby. It
Simplifies the generation of complex SQL queries
Adapts to various RDBMSes
Callbacks
Callbacks can do a variety of tasks, ranging from simple things such as the logging and massaging of attribute values prior to validation to complex calculations.
before_save
before_save :geocode
pluck
The pluck method queries the database for one or more columns of the underlying table of a model.
User.pluck(: id, :name)
Polymorphic has_many Relationships
belongs_to :commentable, polymorphic: true
class Timesheet
enum
Rails 4.1
enum status: %i( draft published archived)
> > Post.new.status = > “draft”