Last active
August 29, 2015 14:05
-
-
Save rishighan/1f3a84958932907e7e8c to your computer and use it in GitHub Desktop.
Constructing queries by merging 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
| @post = Post.hero.group_by_category("include_with_hero", ["General"]) | |
| #Intended result is all posts that fall under the category General AND Hero | |
| #I want this to work with multiple categories, so something like | |
| @post = Post.hero.group_by_category("include_with_hero", ["General", "Foo", "Bar"]) | |
| #should return all posts that fall under General AND Foo AND Bar AND Hero categories |
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
| #scope that isolates "heroes" and "projects" | |
| scope :hero, -> {Post.includes(:categories).where('categories.title = (?)', "Hero")} | |
| scope :projects, -> {Post.includes(:categories).where('categories.title = (?)', "Projects")} | |
| #filter posts by category | |
| def self.group_by_category(action,category) | |
| case action | |
| when "include" | |
| post = Post.includes(:categories).where('categories.title IN (?)', category).order(created_at: :desc).references(:categories) | |
| when "exclude" | |
| post = Post.includes(:categories).where('categories.title NOT IN (?)', category).references(:categories) | |
| when "include_with_hero" | |
| temp = Post.includes(:categories).where('categories.title IN (?)', category).hero | |
| else | |
| post = Post.all | |
| end | |
| end |
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
| @projects = Post.is_draft("no").projects & Post.hero | |
| @posts = Post.is_draft("no").group_by_category("include", ["General", "Technical"]) & Post.hero | |
| #This will give me all posts that are not drafts, that belong to General OR Technical AND Hero. |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the intended result can be achieved by merging scopes, mentioned above.
dang