# Nested models when id is unavailable

**URL:** <https://www.ruby-forum.com/t/nested-models-when-id-is-unavailable/176571>\
**Category:** Rails\
**Created:** [October 2, 2009, 9:50am UTC](https://www.ruby-forum.com/t/nested-models-when-id-is-unavailable/176571 "2009-10-02T09:50:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![scottj97](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e79b87/32.png) [@scottj97](https://www.ruby-forum.com/u/scottj97)\
**Post date:** [October 2, 2009, 9:50am UTC](https://www.ruby-forum.com/t/nested-models-when-id-is-unavailable/176571/1 "2009-10-02T09:50:16Z")

</div>

I have a controller that’s creating model objects from XML input.  
Something like:

 true Scott 

I have two models, StatusReport and Person.

I want to create a new Person iff there is not already one with that  
name. Then, link that Person to this StatusReport.

The built-in accept\_nested\_attributes\_for doesn’t work for me since it  
will always create a new Person unless I provide an id to an existing  
one.

I have full control over the XML input. What I don’t have is a good  
way for it to include the id of an existing Person.

Right now I have a fat controller explicitly looking for a Person,  
then doing Person.create! if needed. I’m sure there’s a better way.

---

<div class="post-metadata">

**Author:** ![scottj97](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e79b87/32.png) [@scottj97](https://www.ruby-forum.com/u/scottj97)\
**Post date:** [October 7, 2009, 12:59am UTC](https://www.ruby-forum.com/t/nested-models-when-id-is-unavailable/176571/2 "2009-10-07T00:59:03Z")

</div>

Just in case anybody cares about the resolution of this, I’ll answer  
my own post.

In my StatusReport model, I added:

def person\_attributes(params = {})  
self.person = Person.find\_or\_initialize\_by\_name(params[:name])  
end

Then I changed the XML to:  
  
true  
  
Scott

This works much like accepts\_nested\_attributes\_for.
