# How to insert data using has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/how-to-insert-data-using-has-and-belongs-to-many/80393>\
**Category:** Rails\
**Created:** [December 25, 2006, 8:28pm UTC](https://www.ruby-forum.com/t/how-to-insert-data-using-has-and-belongs-to-many/80393 "2006-12-25T20:28:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tomukas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d78d45/32.png) [@tomukas](https://www.ruby-forum.com/u/tomukas)\
**Post date:** [December 25, 2006, 8:28pm UTC](https://www.ruby-forum.com/t/how-to-insert-data-using-has-and-belongs-to-many/80393/1 "2006-12-25T20:28:40Z")

</div>

I’am newbie in RoR, so my question might look stupid, but I stuck in one  
thing.

I’ve created 3 tables:

users{  
id,  
user  
}  
books  
{  
id,  
book  
}  
books\_users{  
book\_id,  
user\_id}

Model  
class Book\< ActiveRecord::Base  
has\_and\_belongs\_to\_many:users

I can’t figure out how to insert data to the books\_users table.  
For example users post info about new book and information should be  
stored in the tables books and books\_users.

> > @book = Book.new(params[:book])  
> > @book.user\_ids = @session[‘user’].id  
> > if @book.save

But I get the error message undefined method `each’ for  
#User:0x4cef104  
I know that it is because of the line “@book.user\_ids =  
@session[‘user’].id”, but I can’t userstand how to writte it corectly.  
I’ve red a couple of tutorials but haven’t found a solution.

---

<div class="post-metadata">

**Author:** ![tomukas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d78d45/32.png) [@tomukas](https://www.ruby-forum.com/u/tomukas)\
**Post date:** [December 25, 2006, 10:19pm UTC](https://www.ruby-forum.com/t/how-to-insert-data-using-has-and-belongs-to-many/80393/2 "2006-12-25T22:19:08Z")

</div>

Hi Thomas,

First:  
class User \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :books  
end

@user = User.find 1  
@user.books.create ( :name =\> ‘AWDWR’, :genre =\> ‘rails’ )

Peter

---

<div class="post-metadata">

**Author:** ![tomukas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/d78d45/32.png) [@tomukas](https://www.ruby-forum.com/u/tomukas)\
**Post date:** [December 26, 2006, 12:37am UTC](https://www.ruby-forum.com/t/how-to-insert-data-using-has-and-belongs-to-many/80393/3 "2006-12-26T00:37:34Z")

</div>

Thank you, Peter  
I got it working by changing the line  
@book.user\_ids = @session[‘user’].id  
to  
@book.users \<\< User.find(session[‘user’].id)  
Your code should also work.
