7

私はRubyを使っているのはほんの短い時間で、今日はカレンダーでリクエストを送信しているときに壁にぶつかりました。strftimeを調べるだけでなく、stackoverflowやrubyガイドなどのさまざまな未定義のメソッドエラードキュメントを検索することに時間を費やしました。tryを使用して問題を部分的に解決する解決策を見つけましたが、Railsサーバーが投稿でそれを取得している場合でも、実際にはstrftimeを通過してリクエストに表示されていません。カレンダーにうまくアクセスし、新しいリクエストボタンを押してフォームに入力できますが、そのフォームを投稿すると、ブラウザから次のように表示されます。

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'

これは私のショービューです:

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

最後に、コントローラーの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'

また、ビューデバッグを使用してスキームを確認したところ、すべての属性が正しく並んでいるように見えました。

コメントのリクエストについては、私の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

およびコントローラーアクションコードの作成:

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

私がこれを見ているとき、私のスキーマが複数形であり、私のコントローラーが単数形であるという問題の一部ですか?再度、感謝します。

4

3 に答える 3

17

まず、ActiveRecord検証を適用してレコードを作成する前に、「request_date」が入力されているかどうかを確認する必要があります。

次に、rubyのtryメソッドを使用して、このような例外を回避できます。

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

ハッピーコーディング!

アップデート

新しいバージョンのRubyでは、上記のソリューションの代わりに&.->を使用できます。セーフナビゲーションオペレーターlonely operatorとも呼ばれます。

<%= @vacationrequest&.request_date&.strftime('%B %e, %Y') %>
于 2015-01-03T05:12:37.810 に答える
4

@vacationrequest.request_dateはnilであるため、表示しているレコードに要求日がありません。データが悪いようです。この状況では、次の方法でデバッグします。

  1. ビュー内のダンプ@vacationrequest- <%= debug @vacationrequest %>(またはコントローラーから:) fail @vacationrequest.inspect
  2. Railsコンソールでチェックイン(rails c)-何がVactionrequest.find(some_id)得られますか?
  3. オプションで、DBエントリを確認します。

ただし、休暇のリクエストを入力してもリクエストの日付は保存されないため、createコントローラーアクション、モデルスキーマ、またはモデルの検証にバグがある可能性があります。

于 2012-10-17T21:14:26.890 に答える
0

塩山さん、ご提案ありがとうございました。

:request_date、:presence=>trueを検証します

Railsが推進するデバッグと検証について学ぶことに本当に時間を費やすつもりです。このため、JQueryの日付ピッカーが正しく通過していないことが明確にわかりました。私は自分のassests>javascripts>Vacationrequests.js.coffeeにアクセスし、次のように最後に()を残していることを発見しました。

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

次のように角かっこを削除すると、次のようになります。

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

インデックス作成、表示、編集、更新、新規のすべてが機能しています。すべての提案とこれを実行する方法を教えてくれてありがとう。

于 2012-10-18T13:21:35.203 に答える