如何解决Rails 6 表单不显示错误 - nil:NilClass 的未定义方法 `errors'
我正在尝试向部分内部的用户显示错误。我正在使用以下 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","2"=>{"id"=>"23","3"=>{"id"=>"18","4"=>{"id"=>"19","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]",wrapper_class: 'input simple-radio-buttons'%>
当我删除负责显示错误的行时,它运行良好,但很自然地,我无法向用户显示验证错误。所以问题是如何显示错误并避免这种 undefined method
错误?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。