title: Rails 5: autosave associated record creating duplicate records of the parent model
body: <p>I am currently learning rails and is attempting to create a Survey management application. The application have the following models:</p>
  
  <pre><code>class Survey &lt; ApplicationRecord
    has_many :survey_questions
    has_many :questions, through: : survey_questions
    accepts_nested_attributes_for :questions
  end
  
  class SurveyQuestion &lt; ApplicationRecord
    belongs_to :survey
    belongs_to :question
  end
  
  class Question &lt; ApplicationRecord
    has_many :survey_questions
    has_many :surveys, through: :survey_questions
  end
  </code></pre>
  
  <p>I want to be able to automatically associate existing questions ID to be used instead of creating a whole new list of questions every time I create a new Survey.</p>
  
  <p>I found this solution which was close to what I want <a href="https://stackoverflow.com/questions/3579924/accepts-nested-attributes-for-with-find-or-create">accepts_nested_attributes_for with find_or_create?</a> . It is able to associate my records correctly, but at the end of the transaction it will always create a new record at Question model regardless.</p>
  
  <p>Can anyone suggest why is this happening and help point me to the right direction? Thank you!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Below is the code for my <code>create</code>, <code>new</code> and <code>survey_params</code> method:</p>
  
  <pre><code>def new
    @survey = Survey.new
    @questions = Question.all
  
    unless @question.blank?
      @questions.each do |question|
        @survey.questions.build(name: question)
      end
    end
  end
  
  def create
    @survey = Survey.new(survey_params)
    @survey.save!
  end
  
  def survey_params
    params.require(:survey).permit(:enddate, questions_params: [:name])
  end
  </code></pre>
  
  <p>Below is my view for <code>new</code> and <code>questions_fields</code>, I am using cocoon gem to help me to help generate them dynamically:</p>
  
  <p>new</p>
  
  <pre><code>= simple_form_for @survey, url: survey_index_path, method: :post do |f|
    = f.input :finaldate, as: :string
  
    = f.simple_fields_for :questions do |qn|
      = render 'question_fields', f: qn
  
    = link_to_add_association 'New Question', f, :questions
  </code></pre>
  
  <p>question_fields</p>
  
  <pre><code>= f.input :name
  = link_to_remove_association 'Remove Question', f
  </code></pre>