# Creating/Saving dependent objects

**URL:** <https://www.ruby-forum.com/t/creating-saving-dependent-objects/97591>\
**Category:** Rails\
**Created:** [July 8, 2006, 10:56am UTC](https://www.ruby-forum.com/t/creating-saving-dependent-objects/97591 "2006-07-08T10:56:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sanjay\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f4b2a3/32.png) [@Sanjay\_T](https://www.ruby-forum.com/u/Sanjay_T)\
**Post date:** [July 8, 2006, 10:56am UTC](https://www.ruby-forum.com/t/creating-saving-dependent-objects/97591/1 "2006-07-08T10:56:30Z")

</div>

Folks,

Am new to RoR and am building an example to get myself familiar. I am  
running into a simple issue while creating a user registration page.

I have a User and Address models defined as below (partial/relevant code  
included below). User has\_one address and Address belongs\_to user. I  
have a  
foreign key defined in address table that refers to user(id)

In a form I take in username, password, password\_confirmation and  
address  
fields (add\_user.rhtml below). I then try to populate the data through  
an  
add\_user action in the user\_controller - code included below. For some  
reason I am getting a foreign key violation error as below.

\*class User \< ActiveRecord::Base  
has\_one :address

# validation stuff here

def create\_addr(params)  
address = Address.new(params[:address])  
end\*

_# Other stuff here  
end_

_class Address \< ActiveRecord::Base  
belongs\_to :user  
validates\_presence\_of :street, :city, :zip  
end_

_class UserController \< ApplicationController_

- layout “admin”\*

- def add\_user  
if request.post?  
@user = User.new(params[:user])  
@user.last\_login\_at = Time.now  
@user.create\_addr(params)  
begin  
logger.info("---------------\> Saving user object  
\<-----------------")  
@user.save  
flash[:notice] = “User \*_#{@user.username_ #{@user.username\*}  
created from new function”  
@user = User.new  
rescue Exception =\> e  
flash[:notice] = “Can’t save both address and user”  
flash[:notice] = e.message  
end  
end  
end  
end

- 

_add\_user.rhtml_

   
_\<%= debug(params) %\>  
\<%= error\_messages\_for ‘user’ %\>  
\<%= error\_messages\_for ‘address’ %\>
- Enter User Details\*
- \<%= start\_form\_tag %\>_

_-_ 

_```
 <p>
  Password: <br />
  <%= text_field('user', 'password') %>
</p>*_

_```_

_-_ 

_```
 <p>
  Confirm Password: <br />
  <%= text_field('user', 'password_confirmation') %>
</p>_

_<p>
  Street: <br />
  <%= text_field('address', 'street') %>
</p>*_

_```_

_-_ 

_```
 <p>
  City: <br />
  <%= text_field('address', 'city') %>
</p>*_

_```_

_-_ 

_```
 <p>
  Zip: <br />
  <%= text_field('address', 'zip') %>
</p>_

_<%= submit_tag "Add User", :class => "submit" %> *_

_```_

_- \<%= end\_form\_tag %\>_

 
_\*_

_I get the following error message on the page from the Exception (and  
log  
file)  
Mysql::Error: #23000Cannot add or update a child row: a foreign key  
constraint fails: INSERT INTO users (`hashed_pwd`, `last_login_at`,  
 `salt`,  
 `username`, `firstname`, `lastname`, `address_id`, `company_id`,  
 `login_count`, `created_at`)  
VALUES(‘fce4d31d2ddf5b0ffd122189b9d575362f79c9c9’, ‘2006-07-07  
23:29:09’, ’  
302121320.0514656016603112’, ‘rohant’, ‘’, ‘’, 0, 0, 0, ‘2006-06-11  
01:39:18’)_

 

_The output from debug(params) is as below._

 

_— !ruby/hash:HashWithIndifferentAccess  
user: !ruby/hash:HashWithIndifferentAccess  
password\_confirmation: rohant  
username: rohant  
password: rohant  
commit: Add User  
action: add\_user  
controller: user  
address: !ruby/hash:HashWithIndifferentAccess  
city: San Jose  
zip: “95125”  
street: 7777 Pitkin Ct_

 

_Clearly I am missing something simple here but am not sure what. The  
part I  
am not clear about is how does Rails pick up the fact that the address  
instance needs to be saved automatically when I save the user instance?  
I am  
trying to do something similar to what Dave has done with his Depot  
example  
in his book but obviously something here is not right._

 

_Thanks for any thoughts/pointers you can provide._

 

_Sanjay._

---

<div class="post-metadata">

**Author:** ![Sanjay\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f4b2a3/32.png) [@Sanjay\_T](https://www.ruby-forum.com/u/Sanjay_T)\
**Post date:** [July 8, 2006, 7:11pm UTC](https://www.ruby-forum.com/t/creating-saving-dependent-objects/97591/2 "2006-07-08T19:11:15Z")

</div>

Hi,

You haven’t saved the “address” in your “create\_addr” function.

User needs this id. You can check the SQL’s generated in the  
development.log  
file.

## \_Hari

View this message in context:  
[http://www.nabble.com/Creating-Saving-dependent-objects-tf1910146.html#a5229498](http://www.nabble.com/Creating-Saving-dependent-objects-tf1910146.html#a5229498)  
Sent from the RubyOnRails Users forum at [Nabble.com](http://Nabble.com).

---

<div class="post-metadata">

**Author:** ![Sanjay\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f4b2a3/32.png) [@Sanjay\_T](https://www.ruby-forum.com/u/Sanjay_T)\
**Post date:** [July 8, 2006, 9:29pm UTC](https://www.ruby-forum.com/t/creating-saving-dependent-objects/97591/3 "2006-07-08T21:29:05Z")

</div>

On 7/8/06, Sanjay T. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> In a form I take in username, password, password\_confirmation and address  
> address = Address.new(params[:address])  
> class UserController \< ApplicationController  
> \<-----------------")  
> end  
> Enter User Details
> 
> ```
> <%= submit_tag "Add User", :class => "submit" %>
> 
> ```
> 
> file)  
> — !ruby/hash:HashWithIndifferentAccess  
> street: 7777 Pitkin Ct
> 
> Clearly I am missing something simple here but am not sure what. The part I  
> am not clear about is how does Rails pick up the fact that the address  
> instance needs to be saved automatically when I save the user instance? I am  
> trying to do something similar to what Dave has done with his Depot example  
> in his book but obviously something here is not right.

Truth is that Rails doesn’t know at all most of the time, so your call  
to Address.new needs to be followed up by an Address.save unless you  
create the address by using the special has\_one calls. Rails will  
figure it out if you do User.create\_address(params[:address]) but if  
you create your own address creation function you’ll have to make sure  
that you save too.

Check out the has\_one/many/habtm functions in the docs, there are a  
ton of really awesome prefab functions to do exactly what you’re  
working on.

Also, as you would find out after sorting out the saving problem, the  
address\_id is in the wrong table I believe. foreign\_id always lives in  
the table that belongs\_to the other object. So if address belongs to  
user your address row should have user\_id rather than the user row  
having an address\_id. You can change the structure or just switch the  
has\_one/belongs\_to statements. There’s a good snippet about this on  
the has\_one/many/habtm page of the docs.

[http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html](http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html)

Cheers,  
Chuck V.
