2

I have a MailingList model that has_may :people

For most of my application, I only want to get people that are active

So @mailing_list.people should only return people that are active

In my model, I can't do

def people
  self.people.find_all{ |p| !p.activated_at.nil? }
end

because that keeps calling itself. What is the ruby/rails way to automatically filter the people. Another possible issue is that I think self.people returns an array of active record objects where self.people.find_all... will return an array. This will cause some of my code to break. It's easy fixes but is there a way to return active record objects? It would be nice to have the option.

Thanks!

4

3 回答 3

6

This is a perfect example for a named scope:

class Person < ActiveRecord::Base
  named_scope :active, :conditions => 'activated_at is not null'
end

Then just call it:

# equivalent to Person.find(:all, :conditions => 'activated_at is not null')
@active_people = Person.active 
于 2009-10-15T00:17:49.137 回答
4

You can also filter at the association level.

has_many :people, :conditions => {:activated => true} 
于 2009-10-14T23:28:36.900 回答
0

You can used the standard find method or a dynamic finder. Your find might read as follows:

people.find(:all, :conditions => "activated_at = nil") OR people.find_all(:conditions => "activated_at = nil")

A dynamic version of this might read as:

people.find_by_activated_at(nil)

于 2009-10-14T23:05:24.040 回答