Not logged in (Log in or Sign up)

unwwwritten

an object at rest stays at rest

I think this is kinda nice.

Say you want to use filters and sort orders with a restful controller using something like...

/posts/by/created_at/desc/author/brent

And have this turn into something like...

SELECT * FROM posts WHERE author = 'brent' ORDER BY created_at DESC

Well, now you can.

If you add this named_scope (yet to be pluginified or gemified)...

named_scope :filtered_by, lambda { |filters|
  options = {}
  while f = filters.shift
    if f =~ /^by$/i
      options[:order] << "," if options[:order]
      options[:order] ||= ""
      options[:order] << filters.shift
      options[:order] << " #{filters.shift}" if filters.first =~ /^(asc|desc)$/i
    else
      options[:conditions] ||= {}
      options[:conditions][f.to_sym] = filters.shift
    end
  end
  options
}

Then, add this route...

map.connect '/posts/*filters'

Now, your controller can...

def index
    @posts = Post.filtered_by(params[:filters]).all
end
blog comments powered by Disqus