# HABTM relations insertion

**URL:** <https://www.ruby-forum.com/t/habtm-relations-insertion/107071>\
**Category:** Rails\
**Created:** [June 17, 2007, 6:08pm UTC](https://www.ruby-forum.com/t/habtm-relations-insertion/107071 "2007-06-17T18:08:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![emuen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/96bed5/32.png) [@emuen](https://www.ruby-forum.com/u/emuen)\
**Post date:** [June 17, 2007, 6:08pm UTC](https://www.ruby-forum.com/t/habtm-relations-insertion/107071/1 "2007-06-17T18:08:50Z")

</div>

Hi.

I need to insert a note in my notes table in my mysql db, that is  
related to my users table.

* * *

#user.rb  
has\_many :notes

* * *

* * *

#notes.rb  
has\_many :users

* * *

and i have a table called users\_notes. That looks like this:

* * *

users\_id  
notes\_id

* * *

How do i after saving a note (As under here), make the relation to the  
users table?

* * *

def create  
@notes = Notes.new(params[:notes])  
if @notes.save  
flash[:notice] = ‘Notes was successfully created.’  
redirect\_to :action =\> ‘list’  
else  
render :action =\> ‘new’  
end  
end

* * *

Thanks.  
Emil T. Kampp

---

<div class="post-metadata">

**Author:** ![emuen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/96bed5/32.png) [@emuen](https://www.ruby-forum.com/u/emuen)\
**Post date:** [June 17, 2007, 6:21pm UTC](https://www.ruby-forum.com/t/habtm-relations-insertion/107071/2 "2007-06-17T18:21:43Z")

</div>

First off, you need to use the has\_and\_belongs\_to\_many relationship.

#user.rb  
has\_and\_belongs\_to\_many :notes

Surprisingly, you won’t need anything defined in #notes.rb - all  
handled from the above declaration.

Then in your controller:

@user.notes = Note.new(params[:notes])

A good example can be found here:

[http://jrhicks.net/Projects/rails/has\_many\_and\_belongs\_to\_many.pdf](http://jrhicks.net/Projects/rails/has_many_and_belongs_to_many.pdf)

HTH

Ross

On Jun 17, 5:08 pm, Emil K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
