Добавить данные в таблицу, на которую ссылается внешний ключ в Rails - PullRequest
0 голосов
/ 02 мая 2019

У меня есть две модели: Question и Options.Вопрос имеет отношение has_many к параметрам.Мне нужно добавлять опции в вопрос всякий раз, когда я создаю новый вопрос.Я написал код, но не могу отправить данные в опции модели вопроса.Всякий раз, когда я создаю вопрос и добавляю параметры в форму, параметры этого вопроса пусты.Где ошибка?

Модели

class Question < ApplicationRecord
  belongs_to :user
  has_many :options

  accepts_nested_attributes_for :options
end

class Option < ApplicationRecord
  belongs_to :question
end

questions_controller.rb

# GET /questions/new
  def new
    @question = Question.new
    @question.options.build(params[:options])
  end

  # GET /questions/1/edit
  def edit
  end

  # POST /questions
  # POST /questions.json
  def create
    @question = Question.new(question_params)
    puts("---------------------Question options: --------------------------------------------")
    puts(@question.options)    
    @question.user = current_user

    respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /questions/1
  # PATCH/PUT /questions/1.json
  def update
    respond_to do |format|
      if @question.update(question_params)
        format.html { redirect_to @question, notice: 'Question was successfully updated.' }
        format.json { render :show, status: :ok, location: @question }
      else
        format.html { render :edit }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end

_form.html.erb

<%= form_with(model: question, local: true) do |form| %>
  <% if question.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(question.errors.count, "error") %> prohibited this question from being saved:</h2>

      <ul>
      <% question.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body %>
  </div>

  <%= form.fields_for :address do |a| %>
    <div class="field">
      <%= a.label :option1 %>
      <%= a.text_area :body %>
    </div>

    <div class="field">
      <%= a.label :option2 %>
      <%= a.text_area :body %>
    </div>
  <% end %>


  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

1 Ответ

1 голос
/ 02 мая 2019

В этом случае я настоятельно рекомендую использовать FormObject вместо accepts_nested_attributes_for. Вот краткое видео о том, как реализовать FormObject. https://thoughtbot.com/upcase/videos/form_objects

Кроме того, здесь обсуждается , почему accepts_nested_attributes_for - не лучший вариант.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...