I am learning Rails and have run into a bit of difficulty with something
I suspect is not uncommon, but I'm having difficulty getting my point
across to Google.
I have three models in an application designed to track events in time,
one model (a 'date' model) has a polymorphic relationship to the other
two (the others are two different kinds of events). The other two models
really aren't valid without a corresponding date record. I have chosen
to use a polymorphic association over STI because, as I understand it,
STI is a less efficient approach to the same functionality that a
polymorphic association provides.
The polymorphic relationship that links a date record to one of the
event model records is configured and seems to work okay.
During the initial development process, I was performing object
instantiations and other operations for these objects using two steps,
one step to retrieve the event object, and the second step to retrieve
the date object. Creation operations (and others) were the same way, one
step to create a new event object, the next to create a new date object.
In these operations, the polymorphic association was successfully
providing the desired linkage between the relevant records.
It seemed to me that since the event models aren't valid without a date
model, that the date model should be nested in the event models and the
event models should mediate access to their respective date records.
Therefor when I load one of the event models, it quietly loads its
associated date model. When I want to access the event model's date, I
ask the event model for it, eg. when = expense.bcdate
The problem I have is that when I am creating a new event record, rails
seems intent on saving the date record before saving the event record,
(which seems to make sense to me), and thus the date record's
polymorphic _id field winds up empty at the conclusion of the save
sequence. There seeem to be a lot of different ways to approach this and
I have tried a number of different methods to solve this but they've
either seemed poorly designed or they've ended in failure. I was going
to explain the approaches I've taken but as a neophyte, I thought it
might be better to ask for an approach from the experienced rather than
directing attention to getting the junk code I've written to work.
For what it's worth, here's an abridged version of my models:
class RfBcDate < ActiveRecord::Base
belongs_to :eventage, :polymorphic => true
class RfBcExpense < ActiveRecord::Base
has_one :rf_bc_date, :as => :eventage
RfBcDate.first(:conditions => ["eventage_id = ? AND eventage_type =
?", id, self.class.to_s.pluralize]).bcdate
# An exception is thrown if this isn't present during creation
# When called with in a nested model, the enclosing model isn't
RfBcDate.new(:bcdate => new_date, :eventage_type =>
self.class.to_s.pluralize, :eventage_id => id)