Skip to content

Instantly share code, notes, and snippets.

@flynn1982
Created August 20, 2019 21:10
Show Gist options
  • Save flynn1982/ce2b676b804e85afe3e372a79d9826da to your computer and use it in GitHub Desktop.
Save flynn1982/ce2b676b804e85afe3e372a79d9826da to your computer and use it in GitHub Desktop.
Conditional scope example in rails
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
@flynn1982
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment