views:

20

answers:

1
class Book < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_and_belongs_to_many :users
end


class Category < ActiveRecord::Base
  has_and_belongs_to_many :books
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :books
end

Above is how I declared the relationships between my models. In my book controller and form, I can easily create a book and associate that book with a category. But how do I associate that book with a user on creation time? Is there a part of rails automagic that will supposedly handle this for me or would I have to do some transactional type to update the join table to associate a book with a user.

A: 

You can instantiate a new book like so:

class BooksController < ApplicationController
  def create
    @book = @current_user.books.build(params[:book])
    ...
  end
end

This scopes the book to @current_user; when you save @book, @book.user_id will be set to @current_user.id. How you populate @current_user is up to you.

nfm
I tried this, it saves the to the books table, the join table (books_categories), but no entry is made to the books_users table. I populated the @current_user based on the session_id that I store when the user logs in.
Dhana
Fixed it - to save with correct data, call @current_user.save instead of @book.save
Dhana