HABTM relations insertion

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

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

HTH

Ross

On Jun 17, 5:08 pm, Emil K. [email protected]