Topic: accepts_nested_attributes_for not creating initial foreign key id

Hello,

I am working on an app to track volunteers for an organization. I have made the following models:

models/volunteer.rb

class Volunteer < ActiveRecord::Base

  has_one :homeAddress, :class_name => "Address", :foreign_key => "id", :primary_key => "homeAddress_id"

    attr_accessible :firstName, :lastName, :homeAddress_attributes, :homeAddress

    accepts_nested_attributes_for :homeAddress 
end

models/address.rb

class Address < ActiveRecord::Base
  attr_accessible :city, :line1, :line2, :state, :zip

  belongs_to :volunteer
end

And i have the following DB schema:

Table: volunteers
id:integer
firstName:string
lastName:string
homeAddress_id:integer

Table: addresses
line1:string
line2:string
city:string
state:string
zip:string

My problem is when i do something like:

v = Volunteer.new
v.build_homeAddress
v.homeAddress.line1 = 'test'
v.save

The address is saved and the volunteer is saved, but the 2 are not linked. In the SQL, the volunteer is actually created first. I've been tearing my hair out trying 10000 different things but can't get it to link the two objects.

The strange part is if i go into the database and set the address id manually then it will continue to load and update correctly. So my guess is its somewhat correct.


Any guidance would be greatly appreciated,
Thanks,
- Ken

Re: accepts_nested_attributes_for not creating initial foreign key id

First of all read the documentatnion: http://api.rubyonrails.org/classes/Acti … thods.html
:foreign_key is used to match associated model row ( in your case table addresses should have column 'volunteer_id', you won't need to specify :foreign_key and :primary_id)
Also: use underscore