# Setting values in nested objects

**URL:** <https://www.ruby-forum.com/t/setting-values-in-nested-objects/188030>\
**Category:** Rails\
**Created:** [May 4, 2010, 3:45pm UTC](https://www.ruby-forum.com/t/setting-values-in-nested-objects/188030 "2010-05-04T15:45:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mike](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/58f4c7/32.png) [@mike](https://www.ruby-forum.com/u/mike)\
**Post date:** [May 4, 2010, 3:45pm UTC](https://www.ruby-forum.com/t/setting-values-in-nested-objects/188030/1 "2010-05-04T15:45:08Z")

</div>

Hi,

I have a model with nested objects similar to this:

class Person \< ActiveRecord  
has\_many :addresses  
accepts\_nested\_attributes\_for :addresses  
accepts\_nested\_attributes\_for :home  
end  
class Address \< ActiveRecord  
belongs\_to :person  
has\_one :home  
end  
class Home \< ActiveRecord  
belongs\_to :person  
belongs\_to :address  
end

In my form, I’d like to offer the user the option of selecting the  
address and home from a selection or add a new home/address in a text  
field. If a home/address is selected in the selection, I want to  
ignore the text field. If the renamed blank field is selected, then  
grab the text field. If the value in the text field is already used,  
then reuse the ID. I’d also like to propagate the “address” and  
“person” values to home, but it seems I can only do one or the other  
with build.

I’ve been able to get all the form magic to work, but saving doesn’t  
go as planned. I have to intercept the save, but I’m not sure where  
the best place is. Do I override “new” and “update” or do a  
“before\_save” or … ?

Thanks in advance,  
Mike

---

<div class="post-metadata">

**Author:** ![mike](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/58f4c7/32.png) [@mike](https://www.ruby-forum.com/u/mike)\
**Post date:** [May 5, 2010, 12:54am UTC](https://www.ruby-forum.com/t/setting-values-in-nested-objects/188030/2 "2010-05-05T00:54:49Z")

</div>

Just noticed I had a typo. Forgot to include “has\_many :homes” in  
Person model. Fixed below.

Any advice on where to update the nested objects?

Thanks in advance,  
Mike

---

<div class="post-metadata">

**Author:** ![mike](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/58f4c7/32.png) [@mike](https://www.ruby-forum.com/u/mike)\
**Post date:** [May 5, 2010, 1:14pm UTC](https://www.ruby-forum.com/t/setting-values-in-nested-objects/188030/3 "2010-05-05T13:14:03Z")

</div>

I think this great screencast should do help you :

> **[\#57 Create Model Through Text Field - RailsCasts](http://railscasts.com/episodes/57-create-model-through-text-field)**
>
> Short Ruby on Rails screencasts containing tips, tricks and tutorials. Great for both novice and experienced web developers.
