# Nested Models? Creation Order

**URL:** <https://www.ruby-forum.com/t/nested-models-creation-order/187549>\
**Category:** Rails\
**Created:** [April 25, 2010, 4:27pm UTC](https://www.ruby-forum.com/t/nested-models-creation-order/187549 "2010-04-25T16:27:06Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![xavier](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/2bfe46/32.png) [@xavier](https://www.ruby-forum.com/u/xavier)\
**Post date:** [April 25, 2010, 4:27pm UTC](https://www.ruby-forum.com/t/nested-models-creation-order/187549/1 "2010-04-25T16:27:06Z")

</div>

Hi,

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  
end

class RfBcExpense \< ActiveRecord::Base  
has\_one :rf\_bc\_date, :as =\> :eventage

def bcdate  
RfBcDate.first(:conditions =\> [“eventage\_id = ? AND eventage\_type =  
?”, id, self.class.to\_s.pluralize]).bcdate  
end

# An exception is thrown if this isn’t present during creation

operations  
def bcdate=(new\_date)  
# When called with in a nested model, the enclosing model isn’t  
saved yet.  
RfBcDate.new(:bcdate =\> new\_date, :eventage\_type =\>  
self.class.to\_s.pluralize, :eventage\_id =\> id)  
end  
end

Thanks,  
X.

---

<div class="post-metadata">

**Author:** ![xavier](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/2bfe46/32.png) [@xavier](https://www.ruby-forum.com/u/xavier)\
**Post date:** [April 30, 2010, 2:26pm UTC](https://www.ruby-forum.com/t/nested-models-creation-order/187549/2 "2010-04-30T14:26:18Z")

</div>

Xavier Snark wrote:

> 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.  
> [snip]  
> when I am creating a new event record  
> [snip]

I think you’ve minced some concepts here.

> **[Active Record Associations — Ruby on Rails Guides](https://guides.rubyonrails.org/association_basics.html#polymorphic-associations)**
>
> Active Record AssociationsThis guide covers the association features of Active Record.After reading this guide, you will know: How to declare associations between Active Record models. How to understand the various types of Active Record...

states that you can access the nested model through an instance that has  
a polymorphic association with another model, eg. “From an instance of  
the Employee model, you can retrieve a collection of pictures:  
@employee.pictures.”

Polymorphic associations give you the abilities that you’re after, but  
not entirely. I believe that when you are creating and updating, you  
need to rely on NestedAttributes of the ActiveRecord model in order to  
use a single form for updating both the “subject” record and the related  
record.

> **[ActiveRecord::NestedAttributes::ClassMethods](https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)**
>
> Active Record Nested Attributes Nested attributes allow you to save attributes on associated records through the parent.

I haven’t successfully used this, but the documentation suggests that  
you must update your “subject” model with the  
‘accepts\_nested\_attributes\_for :secondary’ where :secondary is the  
nested model in order to manipulate the related record through the  
subject record’s controller. This gives you the ability to modify the  
related record through values supplied in the request params hash.

X

---

<div class="post-metadata">

**Author:** ![xavier](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/2bfe46/32.png) [@xavier](https://www.ruby-forum.com/u/xavier)\
**Post date:** [May 6, 2010, 3:00pm UTC](https://www.ruby-forum.com/t/nested-models-creation-order/187549/3 "2010-05-06T15:00:33Z")

</div>

Hi X,

Here’s a walkthrough that illustrates what you are after…

[http://docs.google.com/document/pub?id=11q6lGi3p9YBcrGNHSBhkGTNYoFKgKRShxBX\_ynEWQ1c](http://docs.google.com/document/pub?id=11q6lGi3p9YBcrGNHSBhkGTNYoFKgKRShxBX_ynEWQ1c)

X

---

<div class="post-metadata">

**Author:** ![xavier](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/2bfe46/32.png) [@xavier](https://www.ruby-forum.com/u/xavier)\
**Post date:** [May 7, 2010, 2:35pm UTC](https://www.ruby-forum.com/t/nested-models-creation-order/187549/4 "2010-05-07T14:35:33Z")

</div>

Xavier Snark wrote:

> Here’s a walkthrough that illustrates what you are after…
> 
> [Nested Forms & Polymorphic Associations Demonstration](http://docs.google.com/document/pub?id=11q6lGi3p9YBcrGNHSBhkGTNYoFKgKRShxBX_ynEWQ1c)

This page displayer thngy from Google Docs doesn’t seem to work  
perfectly. It keeps truncating the document, so I’ve posted it here as  
well…

> **[Google Sites: Sign-in](https://accounts.google.com/v3/signin/identifier?dsh=S570635037%3A1687925993712027&continue=https%3A%2F%2Fsites.google.com%2Fsite%2Fsites%2Fsystem%2Ferrors%2FWebspaceNotFound%3Fpath%3D%2Fsnarkysday%2Fnestedformspolymorphicassociationsdemonstration&followup=https%3A%2F%2Fsites.google.com%2Fsite%2Fsites%2Fsystem%2Ferrors%2FWebspaceNotFound%3Fpath%3D%2Fsnarkysday%2Fnestedformspolymorphicassociationsdemonstration&ifkv=Af_xneHHRd-Ne6q2exDN6StDB8YdRJws5oGFvvJDzOIbjFPPwXXNGMAT2269efuWDModUpKQev9Ikw&passive=1209600&service=jotspot&flowName=GlifWebSignIn&flowEntry=ServiceLogin)**
>
> Access Google Sites with a personal Google account or Google Workspace account (for business use).

X
