Hien Luong
Hien Luong

Reputation: 520

Rails duplicates records when using ajax to submit the form

My form needs to customize before submitting to the rails. SO, I use ajax to submit the form, but every time, rails doubles records. Anyone has any idea how it happens.

my controller here:

def create
  @school_current = School.find_by_id(params[:school_id])
  @quiz = Quiz.new(params[:quiz])
  @quiz.from_params(params)
  questions = params[:quiz][:questions_attributes]
  questions.each do |index, question|
    @quiz.questions.build(question)
  end

  respond_to do |format|
    if @quiz.save
      format.html { render nothing: true }
    else
      format.html { render action: "new" }
    end
  end
end


def from_params(params)
    self.name = params[:quiz][:name]
    self.school_id = params[:school_id]
    self.description = params[:quiz][:description]
end

form:

<div id="quizzes">
   <%= form_for([@school_current, @quiz], :remote => true) do |f| %>
    <div class="form-inputs" id="quiz_body">
     <div class="form-group">
    <label>Quiz Name (required)</label>
    <%= f.text_field :name, class: "form-control", placeholder: "Enter quiz name here .." %>
</div>
<div class="form-group">
    <label>Quiz Description (optional)</label>
    <%= f.text_area :description, :rows => 10 , :cols => 10, class: "form-control", placeholder: "Enter quiz description here .." %>
</div>
</div>
<div id="question_list">
  <ol>
    <%= f.fields_for  :questions do |builder| %>
        <li class="question_field_item"><%= render "question_fields", f: builder %></li>
    <% end %>
  </ol>
 </div>
  <div class="form-actions">
    <%= f.submit "save quiz", :data => {disable_with: "Saving ..."},class: "btn btn-primary text-uppercase", id: "save_quiz" %>
  </div>
 <% end %>
</div>

Upvotes: 0

Views: 533

Answers (2)

Hien Luong
Hien Luong

Reputation: 520

i figured out the problem. Call question.build twice in both new and create. That's why rails duplicates the record. Remove these lines of code. It will work.

questions.each do |index, question|
   @quiz.questions.build(question)
end

Upvotes: 0

Shiva
Shiva

Reputation: 12582

  • Make sure, single AJAX request is hitting the server
  • the following code block might be the culprit.

respond_to do |format|
  if @quiz.save
    format.html { render nothing: true }
  else
    format.html { render action: "new" }
  end
end

Try extracting the saving from respond_to's block.

if @quiz.save
  respond_to do |format|
    format.html { render nothing: true }
  end
else
  respond_to do |format|
    format.html { render action: "new" }
  end
end

Upvotes: 1

Related Questions