After following a tutorial on gorails to create a nested form, I successfully implemented it. However, my challenge arose when trying to nest a model within another nested model. Initially, I have a main model called Survey
, and then I introduced the Question
model using vue.js for form creation. Next, I added the Choice
model under the question in the survey controller params. My first hurdle is figuring out how to define/implement this in the hello_vue.js file. And secondly, I need to understand how to create form elements in new.html.
This snippet shows my survey.rb model:
class Survey < ApplicationRecord
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions, allow_destroy: true
belongs_to :user
end
and surveys_controller.rb:
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
def survey_params
params.require(:survey).permit(:user_id, :name, questions_attributes:[:id,:survey_id, :title, :qtype, :_destroy, choices_attributes:[:id,:question, :ctext]])
end
end
This section showcases the nested model of Survey - question.rb:
class Question < ApplicationRecord
enum qtype: [:multiple_choice, :check_boxes, :short_answer]
belongs_to :survey
has_many :choices
accepts_nested_attributes_for :choices, allow_destroy: true
end
Finally, here is the vue.js file snippet:
(Code Snippet)
_form.html.erb
<%= content_tag :div,
id: "survey-form",
data: {
survey: survey.to_json(except: [:created_at, :updated_at]),
questions_attributes: survey.questions.to_json,
} do %>
(Additional Code)
<% end %>