Forum: Ruby on Rails Added method to ActiveRecord Class

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Sebastien H. (Guest)
on 2006-04-04 11:17
(Received via mailing list)

Let's say:

class Class2 << ActiveRecord
   belongs_to: class1

class Class1 << ActiveRecord
    has_many :class2s

    def get_max_class2
        ?how to get the max of class2 list ?

I would like to know how I have to write the get_max_class2 method
in order to have the max value of the class2 list ?

I would like to call this method this way:
class2_max = class1.get_max_class2

Any ideas ? Thanks a lot in advance
Rob B. (Guest)
on 2006-04-07 04:14
(Received via mailing list)
On Apr 4, 2006, at 3:15 AM, Sebastien H. wrote:

Well, it does depend on what you really mean by "max", but...

>     def get_max_class2
>         ?how to get the max of class2 list ?
        self.class2s.max	# if <=> is well-defined for Class2
otherwise, the max 'id' like:
        self.class2s.max { |a,b| <=> }
> Regards
> Seb

Of course, you could also:

class Class1 << ActiveRecord::Base
   has_many :class2s
   has_one  :max_class2, :class_name => "Class2", :order => "id DESC"

   # the max_class2 then is free, but if you insist
   def get_max_class2

Look at:

(I did!)


Rob B.
"I sort of keep hoping that red herrings will steadilly come along,
to keep people busy; I get secret satisfaction when bad ideas take
hold and suck a lot of people in ... like Java."
-- Don Knuth, Things a Computer Scientist Rarely Talks About, p.16
(Stanford, California: CSLI Publications, 2001)
This topic is locked and can not be replied to.