Rails 4 fields_for不显示字段

时间:2015-04-25 04:31:01

标签: ruby-on-rails ruby-on-rails-4

我想用一个表单创建两个模型。我尝试了这个railscasts tutorial,但我无法获得在表单上显示的嵌套字段。如何显示这些嵌套字段?

模型

class Poll < ActiveRecord::Base
  has_many :poll_answers, :dependent => :destroy

  accepts_nested_attributes_for :poll_answers, allow_destroy: true
end

class PollAnswer < ActiveRecord::Base
  belongs_to :poll
end

控制器

class PollsController < ApplicationController

  def new
    @poll = Poll.new
    2.times { @poll.poll_answers.build }
  end

  private

  def poll_params
    params.require(:poll).permit([
      :question,
      poll_answers_attributes: [:answer]            
    ])
  end
end

查看

<%= form_for(@poll) do |f| %>

  <div class="field">
    <%= f.label :question %><br>
    <%= f.text_field :question %>
  </div>

  <% f.fields_for :poll_answers do |pa| %>
    <p>Hello
      <%= pa.text_field :answer %>
    </p>
  <% end %>

  <%= debug @poll.poll_answers %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:0)

您错过了=

 <%= f.fields_for :poll_answers do |pa| %>
    <p>Hello
      <%= pa.text_field :answer %>
    </p>
  <% end %>