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