0

I know there is a lot questions like this before, I have following all the answer, but still mine doesn't work. please help.

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

Help? what do I miss?

1
  • any error on console? Commented Feb 18, 2015 at 11:54

1 Answer 1

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

a variable is a hash of attributes which will be passed to a question record. Your question model has no questions field, hence a[:questions] is always blank and the record it is rejected. Instead, do:

:reject_if => :all_blank
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.