Chaining Named Scopes

Posted on November 10, 2008

There aren’t many examples of how to combine named_scopes programmatically on the ol’ Blogosphere these days. All I could find were a few scant references to using anonymous scopes like this. It took me quite a while to figure this out which is surprising since this use case seems like such a common thing to do.

If you want to stack conditions on a search form with will_paginate on top of that, this seems to be the spice.

class Shape < ActiveRecord::Base
    named_scope :created_after, lambda { |m| {:conditions => ["created_at > ?", m]} }
    named_scope :with_color, lambda { |color| {:conditions => {:color => color}} }
end

class ShapesController < ApplicationController
  def index
    scope =  Shape.scoped({})
    scope = scope.created_after(params[:months_ago].to_i.months.ago) if params[:months_ago]
    scope = scope.with_color(params[:color]) if params[:color]
    @shapes = scope.paginate(paginate_options({:order => 'id DESC', :page => 1}))
  end
end

I started to use eval to do this, but Ken Turner set me straight today. I view eval as more of a last resort when all else fails. In this case, it’s possible to tap these filters in using a rubber mallet. No sense in busting out the sledgehammer for this one.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. jtaxx Tue, 16 Dec 2008 17:18:40 UTC

    I can’t even begin to decode ruby but it looks fairly similar to python…

    what have you been working on these days?

  2. Administrator Tue, 16 Dec 2008 19:31:59 UTC

    Building a dolphin decoder for the New Zealand government.

Comments