Skip to content

Instantly share code, notes, and snippets.

@splashinn
Last active May 1, 2020 21:50
Show Gist options
  • Select an option

  • Save splashinn/c32b0586f397cb026ffb47bf8de264f8 to your computer and use it in GitHub Desktop.

Select an option

Save splashinn/c32b0586f397cb026ffb47bf8de264f8 to your computer and use it in GitHub Desktop.
Rails Using ActiveRecord's OR with scopes
class Project < ApplicationRecord
# We have 2 scopes, one for projects In Progress and one for projects Not Started
scope :in_progress, -> {where(project_stage: "In Progress")}
scope :not_started, -> {where(project_stage: "Not Started")}
# Say we want to combine the scopes so we can see projects
# that are in progress or that have been awarded, but not started
# This is where OR is handy :)
scope :project_status, -> {in_progress.or(not_started)}
end
class ProjectsController < ApplicationController
def some_action
# We can call the scope from some action in the controller to get the results
@projects = Project.project_status
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment