如何创建嵌套模型表单

时间:2012-08-03 13:22:14

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

我只是不确定如何构建嵌套表单。我已经关注了Ryan 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的isVisible

这是我在想但似乎没有工作

@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 

它不起作用,也不确定如何创建关系。对它的任何帮助表示赞赏!

这里的查询我做了在rails c

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>

1 个答案:

答案 0 :(得分:1)

你应该使用has_many:through:relationship

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