У меня есть 3 модели: «Опрос», «Вопрос и ответ». «Опрос» - это основная модель, в которую вложен Вопрос, во время создания новой формы я могу создавать и безошибочно редактировать название опроса и его вопросы, тем не менее, я создал представление и метод под названием «take», в котором пользователи должны принять участие в опросе, для этого я вложил «Answer» в Question, а вопрос вложен в Survey, ответы видны в режиме чтения чтобы не сохранять заново или обновлять, во время сохранения этой формы мне нужно сохранить только «Ответы», то есть мне нужно создать новый экземпляр ответа, и сохранить этот ответ, однако я я не могу сделать это, несмотря на то, что добавляю «Answer.new» во вложенность формы, и я вижу, что вы не обращаете внимания на контроллер, особенно в методе Update, каким образом вы могли бы правильно держать вопросы?
take.html.erb
<%= form_with(model: @survey, local: true) do |form| %>
<% 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">
<%= form.object.title %>
</div>
<div class="fields">
<%= form.fields_for :questions do |question| %>
<%= question.object.question_title %>
<ol type="a">
<%= question.fields_for :answers, Answer.new do |answer| %>
<li><%= answer.text_field :response, placeholder: "Reponse" %></li>
<% end %>
</ol>
<% end %>
</div>
<div class="actions">
<br> <%= form.submit %>
</div>
<% end %>
surveys_controller.rb
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :take, :update, :destroy]
def index
@surveys = Survey.all
end
def show
end
def take
end
def new
@survey = Survey.new
@question = @survey.questions.build
end
def edit
@question = @survey.questions.build
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 update
respond_to do |format|
@answer = Answer.new(id: params[:id], response: params[:response], question_id: params[:question_id])
if @survey.update(survey_params)
format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
format.json { render :show, status: :ok, location: @survey }
else
format.html { render :edit }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def destroy
@survey.destroy
respond_to do |format|
format.html { redirect_to surveys_url, notice: 'Survey was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_survey
@survey = Survey.find(params[:id])
end
def survey_params
params.require(:survey).permit(:title, questions_attributes: [:id, :question_title, :survey_id])
end
end
Модель
class Survey < ApplicationRecord
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
class Question < ApplicationRecord
belongs_to :survey
has_many :answers
accepts_nested_attributes_for :answers
end
class Answer < ApplicationRecord
belongs_to :question
end