ruby-on-rails - 在 Rails 中将数据添加到用外键引用的表中
问题描述
我有两个模型: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 %>
解决方案
对于这种情况,我强烈建议使用 aFormObject
代替accepts_nested_attributes_for
. 这是一个关于如何实现FormObject
. https://thoughtbot.com/upcase/videos/form_objects
此外,这里有一个相关的讨论,说明为什么accepts_nested_attributes_for
不是一个好选择。
推荐阅读
- wso2 - 启用 WSO2 IDP 审核日志
- sql - 使用 dateadd 到 datetime 的时间戳是慢查询
- kali-linux - 在kali linux中卸载postgresql-10
- reactjs - 如何模拟作为对函数调用的响应返回的特定对象?
- javascript - 尝试从 Web 服务器位置访问文件时 XMLHttpRequest 访问被拒绝 - IE8
- javascript - 通过 Ajax 插入下拉数据后如何执行 JavaScript?
- html - 响应式表单垂直对齐
- sql-server - 在活动事务上从 SNAPSHOT 切换隔离级别并运行 DDL
- hive - Hive:在共享数据库中创建表时自动将 GRANT SELECT 授予另一个用户
- c# - 升级到 .NET Core 3.0 后“找不到包 Microsoft.NETCore.App.Host.osx-x64”