I am currently learning rails and is attempting to create a Survey management application. The application have the following models:
class Survey < ApplicationRecord
has_many :survey_questions
has_many :questions, through: : survey_questions
accepts_nested_attributes_for :questions
end
class SurveyQuestion < ApplicationRecord
belongs_to :survey
belongs_to :question
end
class Question < ApplicationRecord
has_many :survey_questions
has_many :surveys, through: :survey_questions
end
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.
I found this solution which was close to what I want accepts_nested_attributes_for with find_or_create? . 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.
Can anyone suggest why is this happening and help point me to the right direction? Thank you!
EDIT
Below is the code for my create
, new
and survey_params
method:
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
Below is my view for new
and questions_fields
, I am using cocoon gem to help me to help generate them dynamically:
new
= 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
question_fields
= f.input :name
= link_to_remove_association 'Remove Question', f