开发者

Ruby On Rails Error Can't Convert Nil Into String

I keep getting error can't convert nil into string following is my cod for the the controller and view and new to this any ideas or suggestions as to what could help fix it?

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"

The error when viewing in local host when I try to get the image from the vaiable @img_month

image_tag @img_month, :class => 'img'<---- the error is here yes i did use rails delimeter <%=> but still there is error


The end is probably missing after your first 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

So, @img_month is not set in the daytime.


In your code you don't set @img_month variable if t.hour > 6 && t.hour < 18 is true - it will be nil then.


I guess is it always going through t.hour > 6 && t.hour < 18 true condition, because if it is true, you are not setting a @img_month variable (As the variable sets only in else part).

Having the @img_month in top of your code, before conditions, with a default value would fix your issue.

Note: it's better if you could get these find of presentation logic to helpers. Just pass a value and write a helper to generate your images. And try something @bassneck suggested, as it's more DRY.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜