我第一次尝试通过关联构建包含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%>
my 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的未定义方法`map':NilClass
我尝试按照这篇文章: http://howilearnedrails.wordpress.com/2013/12/18/rails-4-dropdown-menu-with-collection_select/
答案 0 :(得分:0)
请在“books _controller.rb”的“新”操作下添加以下代码段
@authors = Author.all