Skip to content

Fixtures and has_one in Ruby on Rails

In Rails 2.0, fixtures has been improved.  You no longer need to specify ID.  You can check out the screencast.  unfortunately, it does not support the has_one (as far as I can tell).

I have a location object that specifies a phone number, a name, and an address object.  It is specified as follows:

class Location < ActiveRecord::Base
  has_one :address
end

My address class is simply:

class Address < ActiveRecord::Base
end

My address fixture file addresses.yml looks like this:

address1:
  address1: 1234 E Main St
  address2:
  city: Denver
  state: CO
  postal_code: 80014

My locations.yml file looks like:

location1:
  phone: 555-555-5555
  address: address1

If I try to do rake test:units, I get errors saying the ‘address’ column is unknown. Interestingly, if I change the has_one: to belongs_to:, it works just fine.

My work around is to revert to the old style and go ahead and specify ids.

addresses.yml:

address1:
  id: 1
  address1: 1234 E Main St
  address2:
  city: Denver
  state: CO
  postal_code: 80014

locations.yml

location1:
  phone: 555-555-5555
  address_id: 1

Post a Comment

Your email is never published nor shared. Required fields are marked *