Trying to use find my model but I get an error

Hello everyone,

I'm pretty sure that my problem is easy but I've been fiddling with
this for an hour and I cannot see why it's not working

So in my model I defined this method :

  def self.previous
    find(:first, :conditions => ["time
< ?",self.time,self.stop_id], :order => "time DESC")
  end

So I tried my code in the console

and when I do p.previous I get : NoMethodError: undefined method
`find' for #<Passage:0x2100b24>

(p is valid instance of Passage)

Do anyone have an idea ?

Thanks!

Hi David,

Looks like you've defined a class method, but are trying to call it from
an instance of that class. You'd need to call it like: Passage.previous.
Also, if time and stop_id are unique per instance, you'll run into
problems there as well. Not sure what you're trying to accomplish, but
it looks as though you could just make it an instance method (ie: remove
the "self" from def self.previous).

Hope that helps.

Matt

You've declared the method 'previous' to be a *class* method (via the "self."). But then you call it on an *instance* of that class.

Change the method to this:

def previous
   class.find(....)
end

Also, youre conditions specify two arguments, but only one '?' to substitute in a value. And you'll want to remove the "self." from those arguments as well.

-philip

Yeah sorry my fault I posted an old version and didnt look.

What I did is that I created a module called PassageFinder instead

module PassageFinder

  def previous
    find(:first, :conditions => ["time < ?",Time.now], :order => "time
DESC")
  end

  def next
    find(:first, :conditions => ["time > ?",Time.now], :order => "time
ASC")
  end

end

and I extended my relation with it so now I can do
parent.passages.next and it's work :slight_smile:

Thanks tho!

Well yes, I started from an example which I didn't really understand
at first and I tried to "fix it".

You are right that I what I wanted was an instance method but I don't
remember why it was not working yesterday. But after a some digging,
I found that named scope are exactly what I was looking for. They
also take in consideration my associations

So my final solution is :

named_scope :previous, lambda { |limit| { :conditions => ['time
< ?",Time.now'], :limit => limit } }

So now I can do bus_stop.previous.3 and I get the previous 3 passages.