jeudi 5 mars 2015

Rails 3 build changes existing associated record foreign_key to nil

First I wanna applogize for my bad english :)


During work with old rails app I found a problem when writing some specs.


I have 2 models with following relation:



class Customer < ActiveRecord::Base
has_one :key
end

class Key < ActiveRecord::Base
belongs_to :customer

validates :customer_id, :uniqueness => true
end


And factories: 1. for customer 2. for key:



Factory.define :key do |f|
f.association :customer
end


When execute following commands sorcery happens:



customer = Factory(:customer) # creates customer -> ok
key = Factory(:key, :customer => :key) # creates key -> ok
Key.all # 1 key exist eg. => [#<Key id: 1, customer_id:1, ...>] -> ok

# now magic happens
#1
customer.build_key.valid? # => true -> why?
Key.all # 1 key still exists but with customer_id = nil eg. => [#<Key id: 1, customer_id: nil, ...>] -> not ok!
#2
Key.create(customer_id: customer.id) # this is also valid and can be saved to db
Key.all # same as in #1


I have an unique constraint in DB on customer_id column.


My question is why rails changes existing row foreign key to false. Is that a factory girl bug or mby some rails usecase.


I have very old gem versions in this app:



  • rails: 3.0.20

  • factory girl: 2.3.2

  • factory girl rails: 1.4.0


adding



:presence => true


to customer_id validation fixes this issue but I'm still confused why rails changes existing key to nil when building new object.


I also don't know if this kind of 'feature' still exist in newer versions of rails/factory girl cause I didn't checked.


Aucun commentaire:

Enregistrer un commentaire