Forum: Ruby on Rails need to initialize contant arrays , where to do it...

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.
Kad K. (Guest)
on 2008-12-13 18:46
(Received via mailing list)
I need to load names, from the table 'domains' into an array
(frequently used in my app..)
ALL_DOMAINS = Domain.find(:all).map { |d| d.name }.compact

I tried to write it in an initialize or in my application.rb  BUT

problem :  when I run a rake db:migrate initially  (after creating the
database)
I get an error..

rake db:migrate --trace
(in /Users/yves/Developpement/Projects/rails/presdemoi)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
Mysql::Error: Table 'yves_pdm_dev.domains' doesn't exist: SELECT *
FROM `domains`

right, the table is not yet created, that's why I want to do a
migrate ...

any clue ?

thanks
Jeremy W. (Guest)
on 2008-12-14 21:15
Kad K. wrote:
> I need to load names, from the table 'domains' into an array
> (frequently used in my app..)
> ALL_DOMAINS = Domain.find(:all).map { |d| d.name }.compact
>
> I tried to write it in an initialize or in my application.rb  BUT
>
> problem :  when I run a rake db:migrate initially  (after creating the
> database)
> I get an error..
>
> rake db:migrate --trace
> (in /Users/yves/Developpement/Projects/rails/presdemoi)
> ** Invoke db:migrate (first_time)
> ** Invoke environment (first_time)
> ** Execute environment
> rake aborted!
> Mysql::Error: Table 'yves_pdm_dev.domains' doesn't exist: SELECT *
> FROM `domains`
>
> right, the table is not yet created, that's why I want to do a
> migrate ...
>
> any clue ?
>
> thanks

I advise against a constant based on database content. You can do
something functionally equivalent using a class variable to cache the
data the first time it's requested:

class Domain

   def self.cached_names
      @@cached_names ||= Domain.find(:all).map { |d| d.name }.compact
   end

end

Then use Domain.cached_names instead of your constant.

Jeremy
http://jeronrails.blogspot.com
This topic is locked and can not be replied to.