Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom getters in Ruby on Rails

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!

like image 348
Tony Avatar asked Mar 12 '26 12:03

Tony


1 Answers

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 
like image 182
hgmnz Avatar answered Mar 15 '26 02:03

hgmnz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!