Added method to ActiveRecord Class


#1

Hi,

Let’s say:

class Class2 << ActiveRecord
belongs_to: class1
end

class Class1 << ActiveRecord
has_many :class2s

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

end

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
Regards
Seb


#2

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| a.id <=> b.id }

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
self.max_class2
end
end

Look at: http://api.rubyonrails.org/classes/ActiveRecord/
Associations/ClassMethods.html#M000531

(I did!)

-Rob

Rob B.
removed_email_address@domain.invalid

“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)