2011-05-07 99 views
-1

我一直收到錯誤,無法將nil轉換爲字符串,下面是我對控制器和視圖的鱈魚,對此有任何想法或建議可以幫助解決它?Ruby On Rails錯誤無法將Nil轉換爲字符串

class ShowDateTimeController < ApplicationController 
    def display 
    @title = "Some Project For Date and Time" 
    @current_time = Time.now.asctime 
    @current_time2 = Time.now 
    t = Time.now 
    @h= t.hour 
    @m= t.min 
    @s= t.sec 
    @v= Time.now.strftime ("%B") 

    t.hour.to_s 

    if t.hour > 6 && t.hour < 18 
     @img = "sun.jpg" 
     @name = "Good Morning The Sun Is Up" 
    else 
     @img = "moon.jpg" 
     @name = "Good Night The Moon Is Up" 


     if Time.now.month == 1 
     @img_month= "jan.jpg" 
     elsif Time.now.month ==2 
     @img_month = "feb.jpg" 
     elsif Time.now.month ==3 
     @img_month = "mar.jpg" 
     elsif Time.now.month ==4 
     @img_month = "apr.jpg" 
     elsif Time.now.month ==5 
     @img_month = "may.jpg" 
     elsif Time.now.month ==6 
     @img_month = "jun.jpg" 
     elsif Time.now.month ==7 
     @img_month = "jul.jpg" 
     elsif Time.now.month ==8 
     @img_month = "aug.jpg" 
     elsif Time.now.month ==9 
     @img_month = "feb.jpg" 
     elsif Time.now.month ==10 
     @img_month = "oct.jpg" 
     elsif Time.now.month ==11 
     @img_month = "nov.jpg" 
     else 
     @img_month = "dec.jpg" 

在本地主機觀看時,當我嘗試從vaiable @img_month

image_tag @img_month, :class => 'img' <獲取圖像的錯誤----錯誤的是這裏是我沒有用護欄分隔符<%=>但仍有錯誤

+2

你能解決這個缺口,並添加缺少的'end'報表? – 2011-05-07 21:57:35

+0

嘿,只是一個建議:你可以使用像Date :: MONTHNAMES [Time.now.month] [0..2] .downcase +「.jpg」之類的東西來生成文件名 – bassneck 2011-05-07 22:24:18

+1

@bassneck:還有Date :: ABBR_MONTHNAME。但由於某些原因九月有feb.jpg,所以這是行不通的。 – steenslag 2011-05-07 22:35:28

回答

2

end你的第一個if後可能缺失:

if t.hour > 6 && t.hour < 18 
      @img = "sun.jpg" 
      @name = "Good Morning The Sun Is Up" 
    else 
      @img = "moon.jpg" 
      @name = "Good Night The Moon Is Up" 
    end # <---- this one 

因此,@img_month沒有在白天設置。

0

在您的代碼中,如果t.hour > 6 && t.hour < 18爲真,那麼您不會設置@img_month變量 - 那麼它將爲nil

0

我猜是它​​總是會通過

t.hour > 6 && t.hour < 18真實情況,堂妹如果這是真的,你是不是設置@img_month變量(作爲變量集僅else部分)

具有@ img_month在你的代碼之前,在條件之前,使用默認值可以解決你的問題。

注意:如果您能夠將這些演示邏輯發現給幫助者,它會更好。 只是傳遞一個值並編寫一個幫助器來生成圖像。並嘗試一些@bassneck建議。爲更加乾燥

HTH

sameera

相關問題