Проблемы при хранении данных во вложенных формах - Ruby On Rails - PullRequest
0 голосов
/ 25 октября 2018

enter image description here С уважением!Я пытаюсь сделать опрос, все в порядке, однако, когда я создаю опрос и показываю его пользователю, чтобы он мог на него ответить, вопросы распечатывались, а Rails создавал текстовую запись с помощью «Ответить»..new ", в форме опроса, вопросы должны быть напечатаны, и в пределах вопросов, ответы должны быть вложены, однако, по какой-то причине ответ не сохраняется, и я не знаю, что я мог игнорировать, могЯ, возможно, передать какой-то параметр в контроллере?Или, может быть, я неправильно строю форму, я ценю, что вы можете помочь мне:

show.html.erb (опрос)

<p>
  <strong>Name:</strong>
  <%= @survey.name %>
</p>

<%= form_with(model: @survey, local: true) do |f| %>
  <ol>
    <%= f.fields_for :questions do |question| %> <-- nest questions -->
      <li>
        <%= question.object.survey_question %> <-- Print the question -->
        <ul>
          <%= question.fields_for :answers, Answer.new do |answer| %> <-- nest answers -->
            <li><%= answer.text_area :survey_response %> </li>
          <% end %>
        </ul>
      </li>
    <% end %>
  </ol>
  <%= f.submit %>
<% end %>

survey.rb

class Survey < ApplicationRecord
    has_many :questions
    accepts_nested_attributes_for :questions, reject_if: proc { |attributes| attributes['survey_question'].blank? }, allow_destroy: true
end

question.rb

class Question < ApplicationRecord

    belongs_to :survey
    has_many :answers
    accepts_nested_attributes_for :answers, reject_if: proc { |attributes| attributes['survey_response'].blank? }, allow_destroy: true

end

answer.rb

class Answer < ApplicationRecord
    belongs_to :question
end

surveyys_controller.rb

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

  def index
    @surveys = Survey.all
  end

  def show
  end

  def new
    @survey = Survey.new
    question = @survey.questions.build
    question.answers.build
  end

  def edit
    question = @survey.questions.build
    question.answers.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|
      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(:name, :user_id, questions_attributes: [:id, :survey_question, :survey_id, :_destroy, answers_attributes: [:id, :survey_response, :question_id, :_destroy]])
    end
end

rout.rb

Rails.application.routes.draw do

  resources :surveys do
    resources :questions
  end

  resources :questions do
    resources :answers
  end

end

console.log

Started PATCH "/surveys/1" for 127.0.0.1 at 2018-10-24 18:25:36 -0600
Processing by SurveysController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Kd5RuRo9efHvwEzbL4G/j9VAHhXQhu0OKLx0s5YuLHl3w8ZOHcpxqOoMLvVXhXEY82lUb0lQiPhWvpGcP3cosg==", "survey"=>{"questions_attributes"=>{"0"=>{"answers_attributes"=>{"0"=>{"survey_response"=>"a"}}, "id"=>"1"}, "1"=>{"answers_attributes"=>{"0"=>{"survey_response"=>"b"}}, "id"=>"2"}, "2"=>{"answers_attributes"=>{"0"=>{"survey_response"=>"c"}}, "id"=>"3"}}}, "commit"=>"Update Survey", "id"=>"1"}
  Survey Load (4.5ms)  SELECT  "surveys".* FROM "surveys" WHERE "surveys"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/surveys_controller.rb:72
   (0.5ms)  BEGIN
  ↳ app/controllers/surveys_controller.rb:49
  Question Load (2.0ms)  SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = $1 AND "questions"."id" IN ($2, $3, $4)  [["survey_id", 1], ["id", 1], ["id", 2], ["id", 3]]
  ↳ app/controllers/surveys_controller.rb:49
   (0.6ms)  COMMIT
  ↳ app/controllers/surveys_controller.rb:49
Redirected to http://localhost:3000/surveys/1
Completed 302 Found in 33ms (ActiveRecord: 7.5ms)


Started GET "/surveys/1" for 127.0.0.1 at 2018-10-24 18:25:36 -0600
Processing by SurveysController#show as HTML
  Parameters: {"id"=>"1"}
  Survey Load (1.1ms)  SELECT  "surveys".* FROM "surveys" WHERE "surveys"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/surveys_controller.rb:72
  Rendering surveys/show.html.erb within layouts/application
  Question Load (0.6ms)  SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = $1  [["survey_id", 1]]
  ↳ app/views/surveys/show.html.erb:9
  Rendered surveys/show.html.erb within layouts/application (9.1ms)
Completed 200 OK in 83ms (Views: 70.8ms | ActiveRecord: 1.8ms)    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...