I have two tables: class PgmUpdate < ActiveRecord::Base has_many :pgm_visits, :foreign_key => 'pgm_update_fk' ... and class PgmVisit < ActiveRecord::Base belongs_to :pgm_update, :foreign_key => 'pgm_update_fk', :dependent => true ... According to the has_many docs (http://api.rubyonrails.org/classes/ ActiveRecord/Associations/ClassMethods.html#M000471) collection<<(object, â?¦) - adds one or more objects to the collection by setting their foreign keys to the collectionâ??s primary key. But when I add a new, unsaved PgmVisit to an unsaved PgmUpdate the PgmVisit still has a nil foreign key and no pgm_update to show for. Are the docs failing to mention something about unsaved records? I had similar unpredictable problems with WebObjects which is why I am now learning Rails. A related questing is when is the best time to set a custom primary key? Is it required for collection<< to work? I would prefer to not set it if possible since the DB will generate one, but I will if I have to. -John -- John Smilanick Computing Staff - Webmaster Kavli Institute for Theoretical Physics University of California, Santa Barbara firstname.lastname@example.org (805) 893-6307
on 2006-03-14 00:59
on 2006-03-14 01:46
The PgmUpdate object needs to be saved before the foreign keys will get assigned correctly. If possible, save the PgmUpdate before adding any visits. If you are worried about partial lists/info wrap it in a transaction: PgmUpdate.transaction do ...... end You shouldn't need to set any keys manually. Rails/ActiveRecord will take care of it.
on 2006-03-14 17:13
Ok, that sounds reasonable, but is it safe for a transactions to span multiple request-responses? I want a form for users to add visits, but it must be able to rollback the transaction if the form is never submitted or cancelled, do transactions timeout? Should I just work around the problem by associating and saving everything at the last submission? -John -- John Smilanick Computing Staff - Webmaster Kavli Institute for Theoretical Physics University of California, Santa Barbara email@example.com (805) 893-6307