开发者

multiple HABTM relationships in rails

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 u开发者_如何学运维pdate the join table to associate a book with a user.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜