Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

sexy_scopes: Syntactic sugar for ActiveRecord 3.0 and Arel

By Peter Cooper / June 20, 2010

sexy_scope is a small wrapper around Arel::Attribute that adds a little syntactic sugar when creating scopes in ActiveRecord. It adds an attribute class method which takes an attribute name and returns an Arel::Attribute wrapper, which responds to common operators to return predicates objects that can be used as arguments to ActiveRecord::Base.where.

Samuel Lebeau

Some sample code will clear up any confusion:

class Product < ActiveRecord::Base
  scope :untitled, where(attribute(:name) == nil)

  def self.cheaper_than(price)
    where attribute(:price) < price

    where attribute(:name) =~ "%#{term}%"

sexy_scope reimplements Arel attribute methods like lt, in, matches and not using regular Ruby operators.


  1. Jon Leighton says:

    Cool. I gotta say I'm glad he hasn't chosen to add methods to Symbol, which is the approach taken by Mongoid, MongoMapper and DataMapper. Yeah, it's slightly less verbose, but it's so _wrong_!

  2. Ernie Miller says:

    Yeah, I seem to remember him saying he tossed it together because he didn't like that MetaWhere adds methods to symbol. I disagree that it's always evil to do so, particularly when there's little chance of namespace collision and the problem domain being addressed by the gem is well-defined... There's a fine line between best practices and dogma. ;)

Other Posts to Enjoy

Twitter Mentions