我正在尝试向部分内部的用户显示错误。我正在使用以下 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
错误?