[ACCEPTED]-Filtering ActiveRecord queries in rails-activerecord

Accepted answer
Score: 40

What you want are named scopes:

class Item < ActiveRecord::Base
  named_scope :by_author, lambda {|author| {:conditions => {:author_id => author.id}}}
  named_scope :since, lambda {|timestamp| {:conditions => {:created_at => (timestamp .. Time.now.utc)}}}
  named_scope :archived, :conditions => "archived_at IS NOT NULL"
  named_scope :active, :conditions => {:archived_at => nil}
end

In your controllers, use 6 like this:

class ItemsController < ApplicationController
  def index
    @items = Item.by_author(current_user).since(2.weeks.ago)
    @items = params[:archived] == "1" ? @items.archived : @items.active
  end
end

The returned object is a proxy 5 and the SQL query will not be run until 4 you actually start doing something real 3 with the collection, such as iterating (for 2 display) or when you call Enumerable methods 1 on the proxy.

Score: 8

I wouldn't do it like you proposed.

Since 3 find return an array, you can use array 2 methods to filter it, on example:

Item.find(:all).select {|i| i.foo == bar }.select {|i| i.whatever > 23 }...

You can 1 also achive what you want with named scopes.

Score: 2

You can take a look at Searchlogic.
It makes it easier 2 to use conditions on ActiveRecord sets, and even on 1 Arrays.

Hope it helps.

Score: 1

You can (or at least used to be able to) filter 4 like so in Rails:

find(:all, :conditions => { :foo => 'foo', :bar => 'bar' })

where :foo and :bar are 3 field names in the active record. Seems 2 like all you need to do is pass in a hash 1 of :field_name => value pairs.

More Related questions