Custom Getters in Ruby on Rails

I have a MailingList model which has_may: people

For most of my application, I only want to activate active users

So @mailing_list.people

should only return those who are active

In my model, I cannot do

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

      

because he keeps calling himself. What is the rubies / rails method for filtering people automatically. Another possible problem is that I believe self.people returns an array of active record objects, where it self.people.find_all...

returns an array. This will break some of my code. This is easy to fix, but is there a way to get the active record objects back? It would be nice to be able to.

Thank!

+2


source to share


3 answers


You can also filter at the association level.



has_many :people, :conditions => {:activated => true} 

      

+4


source


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 

      

+6


source


You can use the standard search method or the dynamic crawler. Your find might look like this:

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

The dynamic version might look like:

people.find_by_activated_at (zero)

0


source







All Articles