Search code examples
ruby-on-railsactiverecordrails-activerecordaliasnamed-scopes

Can you alias a scope in Rails?


Say I have this scope:

scope :with_zipcode, lambda { |zip| where(zipcode: zip) }

and I want an equivalent scope

scope :has_zipcode, lambda { |zip| where(zipcode: zip) }

is there a way to alias one scope to another? For instance something like

alias :with_zipcode, :has_zipcode

P.S. I know this is a contrived and unrealistic example, just curious to know if it is possible!

Thanks!


Solution

  • Yes you can. Just remember that scopes are class methods so that you need to alias in the context of the class:

    class User < ActiveRecord::Base
      scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
      singleton_class.send(:alias_method, :has_zipcode, :with_zipcode)
    end