【问题标题】:Ruby error: undefined method `[]' for nil:NilClassRuby 错误:nil:NilClass 的未定义方法“[]”
【发布时间】:2016-05-24 08:00:36
【问题描述】:

我正在制作一个两页的时间表提交应用程序。到目前为止,表单可以正常工作,并且您会看到加载图标一秒钟,然后它会移动到感谢页面。尝试重新启动进程并返回第一页时会发生错误。我收到上述错误,它指向以下代码的第 6 行。

class WelcomeController < ApplicationController
  def index
  end

  def show_data
    @email  = params[:timesheet][:email]
    sleep(1.0)
  end
end

这是首页的代码。

<%= stylesheet_link_tag "style.css" %>
<%= javascript_include_tag "code.js" %>

<div class="wrapper">
  <h1>Submit Timesheet</h1>
  <div class="loader">
    <div class="spinner"></div>
  </div>
  <%= form_for :timesheet, :action=>"show_data", :onsubmit => "return validationEvent();" do |f| %>
    <p>
      <%= f.text_field :email, placeholder: "Email:", onFocus: "this.placeholder=''", onBlur: "this.placeholder='Email:'", :id=>"email" %>
      <%= f.label "Invalid Email", :id=>"invalid", :class=>"invalid" %>
      </p>

    <p>
      <%= f.text_area :message, placeholder: "Message (optional):", onFocus: "this.placeholder=''", onBlur: "this.placeholder='Message (optional):'" %>
    </p>

    <p>
      <%= f.label("What type of work is this for?") %>
    </p>

    <div class="container">
      <div class="option">Time working on visual effects for movie</div>
      <div class="option">Time spent reviewing the work of a junior artist</div>
    </div>

    <p>
      <%= f.button "Clear", type: :reset, :id=>"clear" %>
      <%= f.submit "Next", :id=>"next", :onclick =>"return validationEvent();" %>
    </p>

    <%= debug params %>
  <% end %>
</div>

以及完成页面的代码。

<h1> Timesheet Submitted </h1>
<%= form_for :timesheet, :action=>"root" do |f| %>
  Thank you <%= @email %>!
  <p>
    <%= f.button "Start Over", :id=>"restart", :onsubmit=>"index" %>
  </p>
<%= debug params %>
<% end %>

我上网查了一下,还是不知道哪里出错了。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 您有时间表模型吗?如果没有,form_for :timesheetform_for @timesheet 将不起作用。如果您有型号,请分享型号代码。如果没有模型,可以使用 form_tag 并手动生成 params 数组。 form_tag 见apidock.com/rails/ActionView/Helpers/FormTagHelper/form_tag
  • @Anand 这不是真的,您可以使用带符号的表单。
  • 您在show_data 操作中得到什么参数哈希?看来params[:timesheet] 为零
  • @j-dexx - 你是对的。编辑了我上面的评论。

标签: ruby-on-rails ruby


【解决方案1】:

当您返回第一页时,您的参数为空。要修复错误,您可以编写类似

def show_data
    if params.has_key?(:timesheet) && params[:timesheet].has_key?(:email)
        @email  = params[:timesheet][:email]
    end
    sleep(1.0)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2012-12-27
    • 2015-10-18
    相关资源
    最近更新 更多