rails 4 nested_form不保存

时间:2015-02-18 11:49:47

标签: ruby-on-rails ruby nested-forms

我知道之前有很多这样的问题,我已经完成了所有的答案,但我仍然没有工作。请帮忙。

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 %>

帮助?我错过了什么?

1 个答案:

答案 0 :(得分:1)

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

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

:reject_if => :all_blank