How to insert data using has_and_belongs_to_many

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.

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

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.