I''m learning rails and have a test application which parses parts an
XML file to create AR objects and puts them in a database. The IDs in
the database are taken from the XML, i.e. I explicitly set them using
#id. The XML structure is mapped to AR relationships using has_many,
belongs_to etc. I''m using a SAX parser, creating objects when the
element start tag occurs and saving them when the end tag is reached.
This means that child elements get saved before the parent. When the
child element is created it''s belongs_to relationship is set to the
parent object.
I came across a problem when upgrading from 0.8.0 to 0.8.5, which changed:
def id
read_attribute(self.class.primary_key)
end
to
def id
read_attribute(self.class.primary_key) unless new_record?
end
(Ticket 187)
As the parent record hasn''t been saved yet, when I call #save on the
child it can''t get the ID of the parent to insert into the foreign key
field. I''ve worked around this by saving the parent record before I
try to save any children. However I was very confused for a while that
I couldn''t read back the id I had set. Perhaps something like:
the_id = read_attribute(self.class.primary_key)
the_id unless new_record? and the_id.nil?
Would work better??
Chris