0

我第一次尝试通过关联构建一个包含 has_many 的表单,这是我的三个模型:

class Book < ActiveRecord::Base
 has_many :talks
 has_many :authors, through: :talks
 accepts_nested_attributes_for :talks
 accepts_nested_attributes_for :authors
 validates :title, presence: true

end

class Author < ActiveRecord::Base
 has_many :talks
 has_many :books, through: :talks
 validates :l_name ,presence: true
end

class Talk < ActiveRecord::Base
 belongs_to :book
 belongs_to :author
 accepts_nested_attributes_for :author
end

我的书/new.html.erb

<h1>Add new book</h1>
 <%= form_for (@book) do |f| %>
  <div>
   <%= f.label :title %><br>
   <%= f.text_field :title %>
  </div>
  <div>
    <%= f.fields_for :talks, Talk.new do |t| %>
      <div>
        <%t.fields_for :author, Author.new do |a| %>
        <%= a.label :f_name %>
        <%= a.collection_select :f_name, @authors, :f_name, :f_name %>
        <%end %>
      </div>
     <% end%>
    </div>
  <div>
  <%= f.submit %>
  </div>
 <%end%>

我的books_controller.rb

def new
@book =Book.new

end
def create
@book= Book.new(book_params)
if @book.save
  flash[:notice]='goood'
  redirect_to admin_manage_path
else
  flash[:alert]='ouups'
  redirect_to root_url
end
private

 def book_params
params.require(:book).permit(:title, :pages, :resume, authors_attributes: [talks_attributes:   []])
end
end

我收到了这个错误:

nil:NilClass 的未定义方法“map”

我试着关注这篇文章: http ://howilearnedrails.wordpress.com/2013/12/18/rails-4-dropdown-menu-with-collection_select/

4

1 回答 1

0

请在“books_controller.rb”的“新”操作下添加以下片段

@authors = Author.all
于 2014-11-06T12:34:29.850 回答