Skip to content

Instantly share code, notes, and snippets.

@col
Created March 17, 2013 11:46
Show Gist options
  • Save col/5181216 to your computer and use it in GitHub Desktop.
Save col/5181216 to your computer and use it in GitHub Desktop.
A small ActiveRecord concern to help dry up scopes for belongs_to associations.
require 'active_support/concern'
module Scopable
extend ActiveSupport::Concern
module ClassMethods
##
# Creates scopes for all the belongs_to associations provided as args.
# For example 'scope_for :user' creates the following scopes.
#
# def self.for_user(user)
# where(:user_id => user.id)
# end
#
# def self.for_user_id(user_id)
# where(:user_id => user_id)
# end
def scope_for(*association_syms)
association_syms.each do |association_sym|
association = self.reflect_on_association(association_sym)
define_singleton_method("for_#{association.name}") do |object|
where(association.foreign_key.to_sym => object.id)
end
define_singleton_method("for_#{association.name}_id") do |object_id|
where(association.foreign_key.to_sym => object_id)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment