Last active
May 1, 2020 21:50
-
-
Save splashinn/c32b0586f397cb026ffb47bf8de264f8 to your computer and use it in GitHub Desktop.
Rails Using ActiveRecord's OR with scopes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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