# Constants in models are initialized before fixtures are loaded?

**URL:** <https://www.ruby-forum.com/t/constants-in-models-are-initialized-before-fixtures-are-loaded/152587>\
**Category:** Rails\
**Created:** [November 5, 2008, 11:26am UTC](https://www.ruby-forum.com/t/constants-in-models-are-initialized-before-fixtures-are-loaded/152587 "2008-11-05T11:26:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [November 5, 2008, 11:26am UTC](https://www.ruby-forum.com/t/constants-in-models-are-initialized-before-fixtures-are-loaded/152587/1 "2008-11-05T11:26:39Z")

</div>

Hi,

here’s simplified code from the model:  
class Foo \< AR::Base  
FIRST = Foo.first.id  
end

The problem is that when testing I get well known error: “Called id  
for nil…”. I guess that this constant is initialized before the  
fixtures are loaded.

Is there any way to fix it?

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [November 5, 2008, 11:36am UTC](https://www.ruby-forum.com/t/constants-in-models-are-initialized-before-fixtures-are-loaded/152587/2 "2008-11-05T11:36:38Z")

</div>

On 5 Nov 2008, at 10:25, szimek wrote:

> fixtures are loaded.  
> The constant is initialized when the class is loaded which is indeed  
> before the fixtures are. Does it have to be a constant or would

class Foo \< …  
def self.some\_function  
#cache the value and return it  
end  
end

be acceptable?
