If you have a many-to-many association, with the corresponding join table, you must save the model receiving the collection of attribute models prior to using the << or push_with_attributes methods. If you don't do the "pre-save" the records in the joing table will not be created.
For instance,
class Driver < ActiveRecord::Base
has_and_belongs_to_many :policies
end
class Policy < ActiveRecord::Base
has_and_belongs_to_many :drivers
end
drivers
------
id (primary key)
name
dl_num
policies
------
id (primary key)
started_on
coverage
drivers_policies
---------
driver_id (primary key, foreign key)
policy_id (primary key, foreign key)
is_primary_driver
To create the problem:
1) I had an unsaved (no database record, yet) Policy add an unsaved Driver.
@policy.drivers.push_with_attributes(@driver, :is_primary_driver => TRUE)
or
@policy.drivers << @driver
2) Then I saved the Policy
@policy.save
3) Then I looked in the drivers_policies table for a record.
I found that if I call @policy.save prior to adding a collection (either << or push_with_attributes), then the relationships were properly recognized and persisted by a later @policy.save.
I am using Rails 14.3 and PostGreSQL.