# Maintain foreign key linkages in fixtures

**URL:** <https://www.ruby-forum.com/t/maintain-foreign-key-linkages-in-fixtures/63136>\
**Category:** Rails\
**Created:** [June 12, 2006, 5:17pm UTC](https://www.ruby-forum.com/t/maintain-foreign-key-linkages-in-fixtures/63136 "2006-06-12T17:17:13Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![nielsene](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/bc79bd/32.png) [@nielsene](https://www.ruby-forum.com/u/nielsene)\
**Post date:** [June 12, 2006, 5:17pm UTC](https://www.ruby-forum.com/t/maintain-foreign-key-linkages-in-fixtures/63136/1 "2006-06-12T17:17:13Z")

</div>

Is there anyway to refer to the entities being linked in a foreign key  
field of  
a fixture by name instead of id?

Ie, if I have  
categories.yml  
some\_cat:  
id: 1  
name: Foo  
other\_cat:  
id: 2  
name: Bar

data.yml  
some\_item:  
id: 1  
category\_id: \<%= categories(:some\_cat).id %\>  
name: Hello World

The above doesn’t work due to scope, even if the fixtures are loaded in  
the  
proper order. But I think it illustrates what I’d like to do. If the  
objects  
in my fixtures have “good” names, then I’d rather use them when defining  
objects that use them – I can remember the names much better than I can  
remember the arbitrary numbers.

I was able to get something of the form:  
data.yml  
some\_item:  
id: 1  
category\_id: \<%= (Category.find\_by\_name “Foo”).id %\>  
name: Hello World

to work, but that’s adding an extra query to the overhead of  
establishing the  
fixture. I can probably take that hit on the small project I’m working  
on now,  
but on other projects it would probably force me to run smaller suites  
than I’d  
like.

Is there a better way?

Eric
