Forum: Ruby on Rails relationship woes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
858392acd1398aa6071fb1d44cc33842?d=identicon&s=25 John Smilanick (Guest)
on 2006-03-14 00:59
(Received via mailing list)
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
jsmilani@kitp.ucsb.edu
(805) 893-6307
Cb610750ee94ca103aef4b2dc7b1b768?d=identicon&s=25 Nick Stuart (Guest)
on 2006-03-14 01:46
(Received via mailing list)
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.
858392acd1398aa6071fb1d44cc33842?d=identicon&s=25 John Smilanick (Guest)
on 2006-03-14 17:13
(Received via mailing list)
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
jsmilani@kitp.ucsb.edu
(805) 893-6307
This topic is locked and can not be replied to.