rails 4 nested_form 未保存

rails 4 nested_form not saving

我知道以前有很多这样的问题,我已经按照所有的答案,但我的还是不行。请帮助。

survey.rb

# app/models/survey.rb
class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:questions].blank? }, :allow_destroy => true
end

question.rb

# app/models/question.rb
class Question < ActiveRecord::Base
  belongs_to :survey
end

surveys_controller.rb

# app/controllerss/surveys_controller.rb

  def new
    @survey = Survey.new
    @survey.questions.build
  end

  def edit
  end

  def create
    @survey = Survey.new(survey_params)

    respond_to do |format|
      if @survey.save
        format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
        format.json { render :show, status: :created, location: @survey }
      else
        format.html { render :new }
        format.json { render json: @survey.errors, status: :unprocessable_entity }
      end
    end
  end

def survey_params
      params.require(:survey).permit(:name, questions_attributes: [:id, :content, :_destroy])
    end

_form.html.erb

# app/views/surveys/_form.html.erb

<%= nested_form_for @survey do |f| %>
  <% if @survey.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>

      <ul>
      <% @survey.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

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

  <%= f.fields_for :questions do |builder| %>
    <div class="field">
      <%= builder.label :content, "Question" %> <br>
      <%= builder.text_field :content, :rows => 3 %>
      <%= builder.link_to_remove "Remove this question" %>
    </div>
  <% end %>

  <p><%= f.link_to_add "Add a question", :questions %></p>

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

帮忙?我想念什么?

:reject_if => lambda { |a| a[:questions].blank? }

a 变量是将传递给问题记录的属性散列。您的问题模型没有 questions 字段,因此 a[:questions] 始终为空白并且记录被拒绝。相反,做:

:reject_if => :all_blank