# Need to initialize contant arrays , where to do it

**URL:** <https://www.ruby-forum.com/t/need-to-initialize-contant-arrays-where-to-do-it/155569>\
**Category:** Rails\
**Created:** [December 13, 2008, 5:46pm UTC](https://www.ruby-forum.com/t/need-to-initialize-contant-arrays-where-to-do-it/155569 "2008-12-13T17:46:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [December 13, 2008, 5:46pm UTC](https://www.ruby-forum.com/t/need-to-initialize-contant-arrays-where-to-do-it/155569/1 "2008-12-13T17:46:22Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [December 14, 2008, 8:15pm UTC](https://www.ruby-forum.com/t/need-to-initialize-contant-arrays-where-to-do-it/155569/2 "2008-12-14T20:15:41Z")

</div>

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](http://jeronrails.blogspot.com)
