简体   繁体   English

Ruby 未定义的方法 `strftime' for nil:NilClass

[英]Ruby undefined method `strftime' for nil:NilClass

I've only been working with Ruby for a short time and I've hit a wall today while working on a calendar to put requests on.我使用 Ruby 的时间很短,今天我在处理日历以提出请求时碰壁了。 I spent time searching through different undefinied method error documents on stackoverflow, the ruby guides, etc. as well as looking into strftime.我花时间在 stackoverflow、ruby 指南等上搜索不同的未定义方法错误文档,并查看 strftime。 I found a solution that partially solved my problem using try, but now it is not actually passing the strftime through to show on the request, even though the rails server is picking it up in the post.我找到了一个使用 try 部分解决了我的问题的解决方案,但现在它实际上并没有通过 strftime 来显示请求,即使 rails 服务器在帖子中选择了它。 I can get to my calendar fine, and hit the new request button, fill out the form, but when I go to post that form the browsers gives me this:我可以正常访问我的日历,然后点击新的请求按钮,填写表格,但是当我发布该表格时,浏览器给了我这个:

undefined method `strftime' for nil:NilClass

Extracted source (around line #3):

1: <h1><%= @vacationrequest.request_name %></h1>
2: 
3: <p class="info">Requested For <%= @vacationrequest.request_date.strftime("%B %e, %Y") %></p>
4: 
5: <%= simple_format @vacationrequest.message %>
6: 

And I get this error on the Rails server:我在 Rails 服务器上收到此错误:

Started GET "/vacationrequests/1" for 127.0.0.1 at 2012-10-17 15:18:14 -0400
Processing by VacationrequestsController#show as HTML
Parameters: {"id"=>"1"}
←[1m←[35mVacationrequest Load (0.0ms)←[0m SELECT "vacationrequests".* FROM "v
acationrequests" WHERE "vacationrequests"."id" = ? LIMIT 1 [["id", "1"]]
Rendered vacationrequests/show.html.erb within layouts/application (15.6ms)
Completed 500 Internal Server Error in 31ms

ActionView::Template::Error (undefined method strftime' for nil:NilClass):
1: <h1><%= @vacationrequest.request_date %></h1>
2:
3: <p class="info">Requested For <%= @vacationrequest.request_date.strftime(
"%B %e, %Y") %></p>
4:
5: <%= simple_format @vacationrequest.message %>
6:
app/views/vacationrequests/show.html.erb:3:inapp_views_vacationrequests_sho
w_html_erb_217743956_18446544'

This is my show view:这是我的节目观点:

<h1><%= @vacationrequest.request_name %></h1>

<p class="info">Requested For <%= @vacationrequest.request_date.strftime("%B %e, %Y") %></p>

<%= simple_format @vacationrequest.message %>

<p>
  <%= link_to "Edit Request", edit_vacationrequest_path(@vacationrequest) %> |
  <%= link_to "Back to Requests", vacationrequests_path %>
</p>

and this is the _form that the user puts the request information into:这是用户将请求信息放入的_form:

<%= form_for @vacationrequest do |f| %>
  <% if @vacationrequest.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@vacationrequest.errors.count, "error") %> prohibited this request from being saved: if this continue to happens please email the error to alex@allsafeindustries.com</h2>
      <ul>
      <% @vacationrequest.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :request_name %><br />
    <%= f.text_field :request_name %>
  </div>
  <div class="field">
    <%= f.label :request_date %><br />
    <%= f.text_field :request_date %>
  </div>
  <div class="field">
    <%= f.label :message %><br />
    <%= f.text_area :message %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Finally here are my show and index methods in my controller:最后,这是我的控制器中的 show 和 index 方法:

  def index
    @vacationrequests = Vacationrequest.all
    @vacationrequests_by_date = @vacationrequests.group_by(&:request_date)
    @date = params[:date] ? Date.parse(params[:date]) : Date.today
  end

  def show
    @vacationrequest = Vacationrequest.find(params[:id])
  end

Can anybody direct me to what is out of place or why this is nil?任何人都可以指导我什么是不合适的或者为什么这是零? Thank you.谢谢你。

In response to the answer here is what I am now getting from the server:回应这里的答案是我现在从服务器得到的:

Started POST "/vacationrequests" for 127.0.0.1 at 2012-10-17 20:18:00 -0400
Processing by VacationrequestsController#create as HTML
  Parameters: {"utf8"=>"√", "authenticity_token"=>"E1+xXP0pAIQpwMZruswxIZIrTZB3b
c3NlW3iRv9OLqU=", "vacationrequest"=>{"request_name"=>"One more time", "request_
date"=>"10/31/2012", "message"=>"Lucky number 7?"}, "commit"=>"Create Vacationre
quest"}
  ←[1m←[35m (0.0ms)←[0m  begin transaction
  ←[1m←[36mSQL (15.6ms)←[0m  ←[1mINSERT INTO "vacationrequests" ("created_at", "
message", "request_date", "request_name", "updated_at") VALUES (?, ?, ?, ?, ?)←[
0m  [["created_at", Thu, 18 Oct 2012 00:18:00 UTC +00:00], ["message", "Lucky nu
mber 7?"], ["request_date", nil], ["request_name", "One more time"], ["updated_a
t", Thu, 18 Oct 2012 00:18:00 UTC +00:00]]
  ←[1m←[35m (109.2ms)←[0m  commit transaction
Redirected to http://localhost:3000/vacationrequests/7
Completed 302 Found in 125ms (ActiveRecord: 124.8ms)


Started GET "/vacationrequests/7" for 127.0.0.1 at 2012-10-17 20:18:01 -0400
Processing by VacationrequestsController#show as HTML
  Parameters: {"id"=>"7"}
  ←[1m←[36mVacationrequest Load (0.0ms)←[0m  ←[1mSELECT "vacationrequests".* FRO
M "vacationrequests" WHERE "vacationrequests"."id" = ? LIMIT 1←[0m  [["id", "7"]
]
  Rendered vacationrequests/show.html.erb within layouts/application (15.6ms)
    Completed 500 Internal Server Error in 16ms

ActionView::Template::Error (undefined method `strftime' for nil:NilClass):
    1: <h1><%= @vacationrequest.request_name %></h1>
    2: <%= debug @vacationrequest %>
    3: <p class="info">Requested For <%= @vacationrequest.request_date.strftime(
"%B %e, %Y") %></p>
    4:
    5: <%= simple_format @vacationrequest.message %>
    6:
  app/views/vacationrequests/show.html.erb:3:in `_app_views_vacationrequests_sho
w_html_erb___377763931_36688344'

I also used the view debug and checked my scheme and all of the attributes seemed to line up correctly.我还使用了视图调试并检查了我的方案,所有属性似乎都正确排列。

As for the request in the comments here is my Vacationrequest model:至于这里评论中的请求是我的 Vacationrequest 模型:

class Vacationrequest < ActiveRecord::Base
  attr_accessible :message, :request_name, :request_date
end

Once again I can't thank you enough for your help.我再一次感谢你的帮助。

Here is the schema:这是架构:

ActiveRecord::Schema.define(:version => 20121016194123) do

  create_table "vacationrequests", :force => true do |t|
    t.string   "request_name"
    t.date     "request_date"
    t.text     "message"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
  end
end

and the create controller action code:和创建控制器操作代码:

def create
  @vacationrequest = Vacationrequest.new(params[:vacationrequest])
  if @vacationrequest.save
    redirect_to @vacationrequest, notice: "Created Request!"
  else
    render :new
  end
end

As I'm looking at this, is part of the problem my schema being plural and my controller being singular?当我看到这个时,我的模式是复数而我的控制器是单数的问题的一部分吗? Thanks again.再次感谢。

First you have to make sure if there is 'request_date' filled before you create a record by applying ActiveRecord validations.首先,在通过应用 ActiveRecord 验证创建记录之前,您必须确保是否填写了“request_date”。

Secondly, you can use ruby's try method to avoid such exceptions其次,可以使用ruby的try方法来避免此类异常

<%= @vacationrequest.try(:request_date).try(:strftime, '%B %e, %Y') %>

Happy Coding !快乐编码!

Update更新

In the newer version of Ruby, you can use &.在较新版本的 Ruby 中,您可以使用&. -> lonely operator instead of the solution above. -> lonely operator而不是上面的解决方案。 It is also called safe navigation operator .它也被称为安全导航操作员

<%= @vacationrequest&.request_date&.strftime('%B %e, %Y') %>

@vacationrequest.request_date is nil, so the record you're looking at is missing the request date. @vacationrequest.request_date为零,因此您正在查看的记录缺少请求日期。 It sounds like you have bad data.听起来你的数据不好。 In this situation, I'd debug why by:在这种情况下,我会通过以下方式调试原因:

  1. Dumping the @vacationrequest in the view -- <%= debug @vacationrequest %> (or from your controller: fail @vacationrequest.inspect ).在视图中转储@vacationrequest -- <%= debug @vacationrequest %> (或从您的控制器: fail @vacationrequest.inspect )。
  2. Checking in Rails console ( rails c ) -- what does Vactionrequest.find(some_id) yield?检查 Rails 控制台 ( rails c ) -- Vactionrequest.find(some_id)产生什么?
  3. Optionally, checking the DB entry. (可选)检查数据库条目。

However you're inputting vacation requests is not saving request dates, so there's probably a bug in your create controller action, model schema, or model validation.但是,您输入的休假请求并未保存请求日期,因此您的create控制器操作、模型架构或模型验证中可能存在错误。

Shioyama thank you so much for suggesting this: Shioyama 非常感谢你提出这个建议:

validates :request_date, :presence => true验证 :request_date, :presence => true

I'm really going to invest the time in learning about the debugging and validation Rails promotes.我真的打算花时间学习 Rails 所提倡的调试和验证。 Because of this I figured out specifically that the datepicker in JQuery wasn't passing through correctly.因此,我特别发现 JQuery 中的日期选择器没有正确通过。 I went into my assests > javascripts > vacationrequests.js.coffee and found I had left () on the end like this:我进入了我的assests>javascripts>vacationrequests.js.coffee,发现我最后离开了()是这样的:

jQuery ->
  $('#vacationrequest_request_date').datepicker()
    dateFormat: 'yy-mm-dd'

Once I removed the brackets like this:一旦我删除了这样的括号:

jQuery ->
  $('#vacationrequest_request_date').datepicker
    dateFormat: 'yy-mm-dd'

Everything is working, Index, Show, Edit, Update, New.一切正常,索引、显示、编辑、更新、新建。 Thank you both for all the suggestions and showing me how to run this down.感谢你们俩的所有建议,并向我展示了如何解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM