微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 simple_form 中为 nil:NilClass 的 Rails 未定义方法“错误”

如何解决在 simple_form 中为 nil:NilClass 的 Rails 未定义方法“错误”

我正在使用 simple_form 并且我想在部分内部向用户显示错误。为此,我有一个非常简单的形式:

# test_result/shared/_form.html.erb
<%= simple_form_for :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]",collection: q[:answers].map.with_index { |a,i| [a,i.to_s] },as: :radio_buttons %>
    <%= f.input "[#{i}][id]",as: :hidden,input_html: { value: q[:id] } %>
  <% end %>
  <%= f.button :submit,'Submit' %>
<% end %>

它通过以下方式在 new.html.erb 内部呈现:

  <%= render 'test_result/shared/form',url: test_step_one_path,randomize_questions: @randomize_questions  %>

控制器也很标准:

class TestBaseController < SignupBaseController
  before_action :randomize_questions,only: %i[new create]

  def new
    @test_result = TestResult.new
  end

  def create
    @test_result = current_user.test_results.new(
      answer: test_result_params,)

    if @test_result.save
      redirect_to next_step_path
    else
      render :new,status: :unprocessable_entity
    end
  end

private

  def test_result_params
    params.require(:test_results).permit(question_answer_params)
  end

  def question_answer_params
    (0..@randomize_questions.length).each_with_object({}) do |i,hash|
      hash[i.to_s] = %i[id answer question]
    end
  end

这是注册过程中的步骤之一。但是我无法使用此表单显示页面,因为出现以下错误

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? %>

这意味着 f.object = nil - 我传递错误了吗?它应该是什么样子,以便我可以向用户显示错误

[编辑]

我在控制器内添加test_params。当用户未选择任何内容时,question_answer_params生成以下哈希:

# question_answer_params output 
{"0"=>{"id"=>"21","answer"=>""},"1"=>{"id"=>"22","2"=>{"id"=>"23","3"=>{"id"=>"18","4"=>{"id"=>"19","5"=>{"id"=>"20","answer"=>""}}

解决方法

我认为渲染应该是

  <%= render 'test_result/shared/form',url: test_step_one_path,randomize_questions: @randomize_questions,test_results: @test_result %>

形式应该像

<%= simple_form_for @test_result,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]",collection: q[:answers].map.with_index { |a,i| [a,i.to_s] },as: :radio_buttons %>
  <% end %>
  <%= f.button :submit,'Submit' %>
<% end %>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。