2010-08-05 156 views
0
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 

以上是我如何聲明我的模型之間的關係。在我的書籍管理員和表格中,我可以輕鬆創建一本書並將該書與某個類別關聯起來。但是,如何在創建時將該書與用戶關聯起來?有沒有一部分rails automagic會爲我處理這個問題,或者我需要做一些事務類型來更新連接表來關聯一本書和一個用戶。軌道中的多個HABTM關係

回答

0

您可以實例化一個新的書,像這樣:

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取決於你。

+0

我試過了,它保存到書籍表,連接表(books_categories),但沒有對books_users表進行輸入。我根據用戶登錄時存儲的session_id填充@current_user。 – Dhana 2010-08-05 04:43:13

+0

修復了這個問題 - 爲了保存正確的數據,請調用@ current_user.save而不是@ book.save – Dhana 2010-08-07 05:28:52