Forum: Ruby on Rails Loading records during class definition

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ashley M. (Guest)
on 2006-03-30 03:04
(Received via mailing list)
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
Tom M. (Guest)
on 2006-03-30 03:40
(Received via mailing list)
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.
John S. (Guest)
on 2006-03-30 04:25
(Received via mailing list)
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
Ashley M. (Guest)
on 2006-03-31 14:32
(Received via mailing list)
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
This topic is locked and can not be replied to.