association with a model that doesn't have primary key id
-
27-09-2019 - |
Question
I am on Rails 2, which the newest version of factory_girl to use is 1.2.4
I have 2 tables:
ethnicities(code, description)
people(id, name, ..., *ethnicity_code*, ...)
people.ethnicity_code is the foreign key
In factory_girl factories.rb:
Factory.define :ethnicity
f.sequence :code { |n| n+20 }
f.description 'Foo'
end
Factory.define :person do |p|
p.name 'So and so'
...
p.association :ethnicity_code, :factory => :ethnicity
...
end
My models have the correct associations set and "set_primary_key :code"
When I do Factory(:person)
, I always get an insert error due to the foreign key constraint. It would seem that it's getting an incorrect primary key from the association. Factory girl creates the ethnicities record fine, but it's trying to insert a value of "1" as the ethnicity_code in the people table.
Solution
I could be barking up the wrong tree here but I suspect the problem is that p.association :ethnicity_code ...
should be p.association :ethnicity ...
. I.e., you name the association as defined in the model rather than the foreign key column.