Created
August 20, 2019 21:10
-
-
Save flynn1982/ce2b676b804e85afe3e372a79d9826da to your computer and use it in GitHub Desktop.
Conditional scope example in rails
This file contains 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
Some Model Name | |
... | |
# scopes | |
scope :by_category, ->(category) { where(category: category) if category.present? } | |
scope :by_project_id, ->(id) { where(project_id: id ) } | |
... | |
# class methods | |
def self.by_params(category, project_id = nil) | |
docs = ProjectDoc.by_category(category) | |
docs.by_project_id(project_id) if project_id.present? | |
docs | |
end | |
... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspiration:
https://gistpages.com/posts/conditionally-chain-scopes-in-rails