Ruby错误:未定义的方法`[]'为nil:NilClass

时间:2016-05-24 08:00:37

标签: ruby-on-rails ruby

我正在制作两页时间表提交应用。到目前为止,表单工作,你得到加载图标一秒钟,然后它移动到感谢页面。尝试重新启动进程,返回第一页时发生错误。我得到了上面的错误,它指向下面代码的第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 %>

我看过网上但仍无法弄清楚我哪里出错了。非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

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

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