Trying to use find my model but I get an error

1 view
Skip to first unread message

DavidPaquet

unread,
Jun 25, 2008, 10:36:21 PM6/25/08
to Ruby on Rails: Talk
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!

Philip Hallstrom

unread,
Jun 25, 2008, 11:31:15 PM6/25/08
to rubyonra...@googlegroups.com

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

DavidPaquet

unread,
Jun 26, 2008, 12:52:58 AM6/26/08
to Ruby on Rails: Talk
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 :)

Thanks tho!

Matt Payne

unread,
Jun 25, 2008, 11:08:10 PM6/25/08
to rubyonra...@googlegroups.com
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

DavidPaquet

unread,
Jun 26, 2008, 5:32:37 PM6/26/08
to Ruby on Rails: Talk
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.
Reply all
Reply to author
Forward
0 new messages