Loading records during class definition


#1

I’ve created a look-up table in my database that currently has 4
rows. I want to access these as constants in the application because
that’s effectively what they are. I tried this…

class StockRuleLevel < ActiveRecord::Base
has_many :stock_rules

 SITE        = find(:first, :conditions => "type_code = 'site'").id
 MAKE        = find(:first, :conditions => "type_code = 'make'").id
 MODEL       = find(:first, :conditions => "type_code = 'model'").id
 DERIVATIVE  = find(:first, :conditions => "type_code =

‘derivative’").id
end

but find() returns nil. Is there a tidy way of doing what I’m trying
here?

Thanks
Ashley


#2

Can’t answer the question specifically, but I’d recommend you
name the constants with _ID postfix as that’s what they are.

Are you sure you want the ID and not the entire object?


– Tom M.


#3

I tried something similar and had no problem:

class Folks < ActiveRecord::Base

TEST = find(:first,:conditions => “first_name = ‘Fred’”).id
end

in a controller:
p Folks::TEST #outputs 45

-John


John S.
Computing Staff - Webmaster
Kavli Institute for Theoretical Physics
University of California, Santa Barbara
removed_email_address@domain.invalid
(805) 893-6307


#4

Tom -

Actually I suppose it does make sense to store the whole object

John -

Seeing as you got it working I assumed I was doing something stoopid.
Turns
out it’s just the unit tests that break things. Presumably they load
the
class before the fixtures are in place (makes sense) so, in the absense
of a
simpler way of doing thing, I changed the definition to use methods:

class StockRuleLevel < ActiveRecord::Base
has_many :stock_rules
class << self
%w( site make range model derivative thing ).each do |type_code|
eval <<-END_METHOD
def #{type_code.upcase}
StockRuleLevel.find(:first,
:conditions => “type_code = ‘# {type_code}’”)
end
END_METHOD
end
end
end

There’s a section in the pickaxe about caching the results of methods
but I
doubt these will be hit often enough to matter.

Ashley