lundi 15 août 2016

Rails associations for fixtures with foreign_keys/primary_keys

I'm wrestling with Rails fixtures trying to setup my tests but I'm having issues when I try to reference one fixture from another fixture file. The problem started when I changed the association in my model from a belongs_to to a has_one association.

DeviceReplacement.rb - OLD

class DeviceReplacement < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :user
  belongs_to :car

DeviceReplacement.rb - NEW

class DeviceReplacement < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :user
  has_one :active_car, primary_key: 'car_id', foreign_key: 'id', class_name: 'Car'

device_replacements.yml

mikes_device_replacement:
  old_device_number: "bdh9fa023bf6851cb8eb95hbd0d1019"
  new_device_number: "poe9fa023bf6851cb8eb95hbd0d939"
  return_status: "envelope sent"
  cancel_date: <%= Date.today %>
  subscription: mike_car_subscription
  car: mike_car
  user: mike

cars.yml

mike_car:
  model: 'XT-2000-G-X001'
  phone_number: '5551231238'
  device_number: 'bdh9fa023bf6851cb8eb95hbd0d1019'
  uid: 19191919191919
  lt: 25.782324
  ln: -80.2310801
  pricing_plan_id: 75
  title: "Mike's Car"
  status: "onboarded"
  device_purchase: mikes_purchase

I'm now getting the following error -

Ryans-MacBook-Pro:myautobrain ryangrush$ rake db:fixtures:load RAILS_ENV=test
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "car" of relation "device_replacements" does not exist
LINE 1: ...w_device_number", "return_status", "cancel_date", "car", "cr...
                                                             ^
: INSERT INTO "device_replacements" ("old_device_number", "new_device_number", "return_status", "cancel_date", "car", "created_at", "updated_at", "id", "subscription_id", "user_id") VALUES ('bdh9fa023bf6851cb8eb95hbd0d1019', 'poe9fa023bf6851cb8eb95hbd0d939', 'envelope sent', '2016-08-15', 'mike_car (Car)', '2016-08-15 17:46:15', '2016-08-15 17:46:15', 219175143, 88066445, 350169046)

I can get it to work if I hard code the :id for each but I'm trying to avoid doing that.

Aucun commentaire:

Enregistrer un commentaire