Skip to content
CodeMeister edited this page Feb 28, 2023 · 1 revision

default scopes:

By default two ActiveRecord::Scope are created for each state, making searching by state super easy.

One scope will select all records that match the state...

scope :draft, ~>{ where(status: 'draft') }

...and the other will select all records that do not match the state.

scope :not_draft, ~>{ where.not(status: 'draft') }
class Post < ActiveRecord::Base
  include StateGate

  state_gate :status do
    state :draft
    state :pending
    state :published
    state :archived
  end
end

draft_post     = Post.create
published_post = Post.create(status: :force_published)

Post.draft.include?(draft_post)          #=> true
Post.draft.include?(published_post)      #=> false

Post.not_draft.include?(draft_post)      #=> false
Post.not_draft.include?(published_post)  #=> true

no scopes:

Scopes can be turned off with the no_scopes option

class Post < ActiveRecord::Base
  include StateGate

  state_gate :status do
    state :draft
    state :pending
    state :published
    state :archived

    no_scopes
  end
end

Post.draft  #=> <NoMethodError>