Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic associations in ruby on rails fixtures

As described in this article, I am using automatic associations in fixtures. For example, if a region object has a country id, instead of doing "country_id": 1, I do "country": "USA". "USA" is a label in my countries.yml file, so fixtures knows how to take care of this. However, this only works when you do not specify an ID value for the countries object. So I cannot assign USA's ID to be 1. But if I do not assign it to be 1, it ends up being some large value 8974343...which is kinda strange. Is there a way to get fixtures to auto-generate id's that are not super high? ....or is this ok?

like image 787
Tony Avatar asked Apr 18 '09 18:04

Tony


3 Answers

This is how you get an autogenerated id of the fixture label.

Fixtures.identify(:reginald)
like image 76
crazycrv Avatar answered Nov 10 '22 03:11

crazycrv


Reading the API documentation, this is exactly how autogenerated fixtures are supposed to behave -- if you want to have a specific ID value for a fixture in advance, you should probably just assign it yourself.

If not, well, from the API docs:

The generated ID for a given label is constant, so we can discover any fixture‘s ID without loading anything, as long as we know the label.
like image 44
Don Werve Avatar answered Nov 10 '22 04:11

Don Werve


Since I don't have enough reputation to comment, this is the actual Rails 4.1 documentation:

http://edgeapi.rubyonrails.org/classes/ActiveRecord/FixtureSet.html#class-ActiveRecord::FixtureSet-label-Fixture+label+interpolation

Under Fixture label interpolation:

monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
like image 17
Edo Avatar answered Nov 10 '22 05:11

Edo