ruby-on-rails - Rails 6 表单不显示错误 - nil:NilClass 的未定义方法“错误”
问题描述
我试图在部分内部向用户显示错误。我在下面使用simple_form
:
<%= simple_form_for :appropriateness_test_results, url: url do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<% randomize_questions.each_with_index.map do |q, i| %>
<%= f.input "[#{i}][answer]", label: "#{i+1}. #{q[:question]}", collection: q[:answers].map.with_index { |a, i| [a, i.to_s] }, as: :radio_buttons, wrapper_class: 'input simple-radio-buttons'%>
<% end %>
<%= f.button :submit, 'Submit' %>
<% end %>
在里面渲染new.html.erb
<%= render 'appropriateness_test/shared/form', url: appropriateness_test_step_one_path, randomize_questions: @randomize_questions %>
控制器内部没有什么特别之处:
module AppropriatenessTest
class BaseController < SignupBaseController
before_action :randomize_questions, only: %i[new create]
include AppropriatenessTest::ParserHelper
def new
@appropriateness_test_result = AppropriatenessTestResult.new
end
def create
@appropriateness_test_result = current_user.appropriateness_test_results.new(
answer: user_answers,
)
if @appropriateness_test_result.save
redirect_to next_step_path
else
render :new, status: :unprocessable_entity
end
end
# user_answers output
{"0"=>{"id"=>"21", "answer"=>""},
"1"=>{"id"=>"22", "answer"=>""},
"2"=>{"id"=>"23", "answer"=>""},
"3"=>{"id"=>"18", "answer"=>""},
"4"=>{"id"=>"19", "answer"=>""},
"5"=>{"id"=>"20", "answer"=>""}}
这是注册过程中的步骤之一。但我无法使用此表单显示页面,因为出现以下错误:
undefined method errors for nil:NilClass
Extracted source (around line #3):
1 <%= simple_form_for :appropriateness_test_results, url: url do |f| %>
2 <%= f.error_notification %>
3 <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
4
5 <% randomize_questions.each_with_index.map do |q, i| %>
6 <%= f.input "[#{i}][answer]", label: "#{i+1}. #{q[:question]}", collection: q[:answers].map.with_index { |a, i| [a, i.to_s] }, as: :radio_buttons, wrapper_class: 'input simple-radio-buttons'%>
当我删除负责显示错误的行时,它运行良好,但自然而然,我无法向用户显示验证错误。所以问题是如何显示错误并避免这种undefined method
错误?
解决方案
推荐阅读
- postgresql - 如何在 PostgreSQL 9.4 上将 int4range 类型的列转换为整数?
- php - 自定义 WooCommerce 我的帐户和结帐上的地址字段
- vhdl - 跨块语句的 VHDL 配置
- git - 在 git merge workingbranch 之后,如何去除错误“error: cannot run sublime: No such file or directory”
- python - 使用熊猫对浮点列进行分组
- nativescript - 无法在 iOS 上运行应用程序 Nativescript 但在 android 上运行
- android - 错误:无法解决:com.github.hatamiarash7:RTL-Toast:1.3
- node.js - firestore node.js sdk 在写入时停止响应
- c# - 用被破坏的六边形替换六边形
- java - 运行项目时缓存内存未将值保存在缓存中