【问题标题】:has_many :through association and form_forhas_many : 通过关联和 form_for
【发布时间】:2014-10-22 21:15:07
【问题描述】:

我第一次尝试通过关联构建一个包含 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/

【问题讨论】:

    标签: ruby-on-rails-4 nested-form-for


    【解决方案1】:

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

    @authors = Author.all
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      相关资源
      最近更新 更多