0

我只是不確定如何構建嵌套表格。我跟着瑞安Railscasts,但我不確定如何在我的情況下創建一個新的實例。如何創建嵌套模型表格

我有以下型號

Customer, 
Book Manager, and 
Book 

他有關係遵循

Customer 
    has_many :book_managers, :dependent => :destroy 
    accepts_nested_attributes_for :book_managers 
Book 
    belongs_to :book_manager 
    def customer 
     book_manager.customer 
    end 
Book_Manager 
    belongs_to :customer 
    has_many :books, :dependent => :destroy 

他的形式遵循

<%= form_for @bookmanager do |f| %> 
    <%= f.fields_for :books, Book.new do |builder| %> 
    <div> 
    <%= builder.label :description %><br /> 
    <%= builder.text_area :description, :rows => 3 %> 
    </div> 
    <% end %> 
    <div class="field"> 
    <%= f.label :visible %><br /> 
    <%= f.text_field :visible %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

是困惑我自己創建一個新的部分實例以單一形式。我有屬於預定的描述,我有誰所屬的可見性,以book_managers

這裏我在想什麼,但似乎並不奏效

@customer = Customer.find(params[:id]) 
@bookmanager = BookManager.new(params[:bookmanager]) 
@book = Book.new(params[:book]) 

我也嘗試以下

@customer = Customer.find(params[:id]) 
@bookmanager = @customer.book_managers.build 

它不工作,不知道如何創建關係。任何對此的幫助表示讚賞!

這裏查詢我確實在軌道ç

cust = Customer.first 
cust.book_managers.build :visible => true 
cust.book_managers.first.books.build :description => 'the odyssey' 
cust.save! 

看起來好,然後我做了後續檢查

cust = Customer.find 1 
cust.books    ### This is where the error was given to me 
Book.first.customer 

的錯誤是

NoMethodError: undefined method `books' for #<Customer:0xad55afc> 
+0

它是否在控制檯上出現錯誤? – MurifoX 2012-08-03 13:47:40

+0

它現在。我更新了什麼顯示錯誤看起來像 – Jseb 2012-08-03 14:05:33

+0

以下Railscasts教程我不應該添加客戶關係 - >書籍。但許多其他人似乎建議用has_many來這樣做。他最好的辦法是什麼,我應該如何創建一個新的項目。我對Ruby如何行爲非常困惑。 – Jseb 2012-08-03 14:13:16

回答

1

您應該使用的has_many :通過:關係

class Customer < ActiveRecord::Base 
    has_many :book_managers, :dependent => :destroy 
    has_many :books, :through => :book_managers 
    accepts_nested_attributes_for :book_managers 
end 

class BookManager < ActiveRecord::Base 
    belongs_to :customer 
    has_many :books, :dependent => :destroy 
end 

class Book < ActiveRecord::Base 
    has_many :book_manager 
    def customer 
    book_manager.customer 
    end 
end 

您可以閱讀更多http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many