Can I has_scope?!

has_scope is a nice gem for Rails applications created by plataformatec. You can find it on github. The purpose of has_scope is to dynamically retrieve data from a model by applying the model’s scopes.

For example say we have a Post model with the attribute title, body, and then category and a Posts controller. We want the Posts controller to retrieve posts for different categories. Instead of writing different actions or handling any params passed in manually, we can use has_scope. Here’s how:

Post Model

class Post < ActiveRecord::Base
  ...
  scope :by_category, lambda { |category| where(category: category) }
  ...
end

Posts Controller

class PostsController < ApplicationController
  ...
  has_scope :by_category, only: :index
  ...
  def index
    @posts = apply_scopes(Post).all
  end
end