Skip to content

Instantly share code, notes, and snippets.

@rishighan
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save rishighan/1f3a84958932907e7e8c to your computer and use it in GitHub Desktop.

Select an option

Save rishighan/1f3a84958932907e7e8c to your computer and use it in GitHub Desktop.
Constructing queries by merging scopes.
@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
#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
@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.
@rishighan
Copy link
Author

So the intended result can be achieved by merging scopes, mentioned above.
dang

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