Chaining Named Scopes
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.







I can’t even begin to decode ruby but it looks fairly similar to python…
what have you been working on these days?
Building a dolphin decoder for the New Zealand government.