首页 > 解决方案 > 在 Rails 中将数据添加到用外键引用的表中

问题描述

我有两个模型:QuestionOptions. 问题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 %>

标签: ruby-on-rails

解决方案


对于这种情况,我强烈建议使用 aFormObject代替accepts_nested_attributes_for. 这是一个关于如何实现FormObject. https://thoughtbot.com/upcase/videos/form_objects

此外,这里有一个相关的讨论,说明为什么accepts_nested_attributes_for不是一个好选择。


推荐阅读