Web Development

Scopes are ways to easily retrieve information by creating callable methods on the model. These callable methods are in turn methods that represent queries. These scopes when used return ActiveRecord::Relation that you can chain with other scopes.

class Incident < ActiveRecord::Base
  scope :draft_incidents, -> { where(draft: true)}
  scope :verified_incidents, -> { where(verified: true)}
  scope :this_year, -> {where("EXTRACT(YEAR FROM incidents.incident_date) = ?", Time.now.year)}
end

To chain scopes you can simply concatenate them using dots

Incident.this_year.draft_incidents
[1] pry(main)> Incident.this_year.draft_incidents
  Incident Load (23.6ms)  SELECT "incidents".* FROM "incidents" WHERE "incidents"."deleted_at" IS NULL AND (EXTRACT(YEAR FROM incidents.incident_date) = 2016) AND "incidents"."draft" = $1  [["draft", "t"]]
=> []

To conditionally chain scopes you can do this.

def some_method
  @incidents = Incident.all
  @incidents = @incidents.draft_incidents unless params[:draft].nil?
  @incidents = @incidents.draft_incidents unless params[:this_year].nil?
end

So unless the params are available, you would get all incidents in the table.