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
以上是我如何声明模型之间的关系。在我的book controller和form中,我可以轻松地创建一本书,并将该书与一个类别相关联。但是,如何将该书与创建时的用户相关联?rails automagic是否有一部分应该为我处理这个问题,或者我是否需要执行一些事务类型来更新连接表以将一本书与一个用户关联起来。
你可以这样实例化一本新书:
class BooksController < ApplicationController def create @book = @current_user.books.build(params[:book]) ... end end
@current_user ; 当你保存 @book , @book.user_id 将设置为 @current_user.id . 如何填充 @当前用户 随你。
@current_user
@book
@book.user_id
@current_user.id
@当前用户