ruby-on-rails - Ruby 未定义方法 `strftime' 为 nil :NilClass

标签 ruby-on-rails ruby ruby-on-rails-3 methods null

我只使用 Ruby 工作了很短的时间,今天我在处理日历以提出请求时遇到了瓶颈。我花时间在 stackoverflow、ruby 指南等上搜索不同的未定义方法错误文档,并研究了 strftime。我找到了一个使用 try 部分解决我的问题的解决方案,但现在它实际上并没有通过 strftime 来显示请求,即使 rails 服务器在帖子中拾取它。我可以正常访问我的日历,然后点击新请求按钮,填写表格,但是当我去发布该表格时,浏览器会给我这个:

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: 

我在 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'

这是我的展示 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>

这是用户将请求信息放入的_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 %>

最后是我的 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

任何人都可以告诉我哪里不合适或者为什么这是零吗?谢谢。

响应这里的答案是我现在从服务器得到的:

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'

我还使用了 View 调试并检查了我的方案,所有属性似乎都正确排列。

至于这里评论中的请求是我的 Vacationrequest 模型:

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

再一次感谢您的帮助。

这是架构:

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

和创建 Controller 操作代码:

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

当我看到这个时,问题的一部分是我的模式是复数而我的 Controller 是单数吗?再次感谢。

最佳答案

First you have to make sure if there is 'request_date' filled before you create a record by applying ActiveRecord validations.

Secondly, you can use ruby's try method to avoid such exceptions

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

编码愉快!

更新

在较新版本的 Ruby 中,您可以使用 &. -> lonely operator 代替上述解决方案。它也被称为安全导航运算符

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

关于ruby-on-rails - Ruby 未定义方法 `strftime' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943362/

相关文章:

ruby-on-rails - "rails s"使用 Ruby 1.8.7 而不是 Ruby 1.9.3 (OS X 10.7.2)

ruby-on-rails - Ruby 中的绝对符号是什么意思?

ruby-on-rails - 如何使用在助手中定义的函数到脚手架生成模板中?

ruby-on-rails - Rails 与同一模型的多个 Has_one 关系

ruby - Rails 3 查询 : Find all Posts with the same Topic

ruby-on-rails - 建模多对多 :through with Mongoid/MongoDB

ruby-on-rails - 从 Rakefile/Ruby on Rails 3 中的模型访问类方法

javascript - 当我收到 200 响应时,CoffeeScript 一直触发错误?

html - rails 5 中具有线性渐变的背景图像

ruby - 使用 WebDriver 和 Ruby 与 JavaScript 下拉菜单交互?