"xxx_id may not be null" when saving many to many joined objects

Hi,

I have two model classes; Tune and Title and they are joined in a many to many relationship through a Variation class. Here's some stub code of the models:

class Tune < ActiveRecord::Base   has_many :variations, :dependent => :destroy   has_many :titles, :through => :variations ... class Title < ActiveRecord::Base   has_many :variations, :dependent => :destroy   has_many :tunes, :through => :variations ... class Variation < ActiveRecord::Base   belongs_to :tune   belongs_to :title ...

In my TunesController I create a new Tune, Variation and Title. I set the :tune and :title attributes in the Variation, and add the Variation to the tune and title's :variations arrays.

The problem is that when I save the Tune, I get the following error: SQLite3::SQLException: variations.title_id may not be NULL: INSERT INTO "variations" ("updated_at", "title_id", "tune_id", "created_at") VALUES('2008-09-18 12:21:52', NULL, NULL, '2008-09-18 12:21:52')

I assumed that Rails would know that the Tune, Variation and Title are all new objects and perform the save of the Tune and Title, get their IDs to store in the Variation and lastly save the Variation.

Any help or pointers for where to look are greatly appreciated.

Thanks, Pat

Hi,

fixed the problem. I added the Variation to the 'created' Tune before I had added the Title to the Variation. So the Variation obviously didn't have a Title object with which an id could be derived/created.

Cheers Pat