Forum: Ruby on Rails Class method finder and undefined method from association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris B. (Guest)
on 2009-01-12 03:45
(Received via mailing list)
I'm trying to create a method on a model (Note) that finds a subset of
records, but banging my head against a brick wall. The code so far:

class Note
  belongs_to :person

  def self.can_be_viewed
    find(:all, :conditions => ["notes.created_at <= ?",
person.cutoff_date])
  end
  ...

class Person
  has_many :notes

  def cutoff_date
    ...
  end
  ...

Ultimately I want to be able to use @person.notes.can_be_viewed, but
I'm getting an "undefined local variable or method `person' for
#<Class:0x8ed10b8>" error. This isn't surprising - the can_be_viewed
method is a class method, so has no way of accessing
person.cutoff_date in the finder.

All I'm really trying to say here is:
1. A person has a cutoff date (this can vary according to who the
logged-in user is, but that's irrelevant, although the cutoff_date
method generates some SQL).
2. Notes can be viewed if they are created before their person's
cutoff_date (note.person.cutoff_date).

I'd appreciate any thoughts on this.
Frederick C. (Guest)
on 2009-01-12 09:19
(Received via mailing list)
On Jan 12, 1:44 am, Chris B. <removed_email_address@domain.invalid> wrote:
> I'm trying to create a method on a model (Note) that finds a subset of
> records, but banging my head against a brick wall. The code so far:
>

You need to join the people table, eg,

find :all, :joins => :person, :conditions => ["notes.created_at <=
people.cutoff_date"]

Fred
Chris B. (Guest)
on 2009-01-18 08:28
(Received via mailing list)
Thanks Fred. That hasn't done it (I had tried joins), but I'll keep
working on it.

On Jan 12, 8:18 pm, Frederick C. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.