Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date.new returns undefined method `div' for "11":String

I am getting the error

undefined method `div' for "11":String"

pointing to the @startdate line when I submit the form. I don't understand what's going on at all. If I do the steps in the rails console it works fine.

In my controller I have:

@startday = params["startday_#{i}".to_sym]
@startmonth = params["startmonth_#{i}".to_sym]
@startyear = params["startyear_#{i}".to_sym].to_s
@endday = params["endday_#{i}".to_sym]
@endmonth = params["endmonth_#{i}".to_sym]
@endyear = params["endyear_#{i}".to_sym].to_s
@startdate = params["startdate_#{i}".to_sym]
@price = params["price_#{i}".to_sym]
@currency = params[:currency]
@startdate = Date.new(@startyear, @startmonth, @startday)
@enddate = Date.new(@endyear, @endmonth, @endday)

The hash I am sending is:

{
  "startmonth_1"=>"2",
  "startday_1"=>"11",
  "startyear_1"=>"12",
  "endmonth_1"=>"2",
  "endday_1"=>"13",
  "endyear_1"=>"12",
  "price_1"=>"12",
}

If I do a

@startee = @startyear.to_s + '-' + @startmonth.to_s + '-' + @startday
return render :text => @startee

I get:

12-2-11

So I don't see the problem. Everything seems to be working ok.

like image 853
Tim Reistetter Avatar asked Sep 19 '12 00:09

Tim Reistetter


1 Answers

You're passing strings to Date.new when you need to pass integers:

@startday = params[:"startday_#{i}"]
@startmonth = params[:"startmonth_#{i}"]
@startyear = params[:"startyear_#{i}"].to_s
@endday = params[:"endday_#{i}"]
@endmonth = params[:"endmonth_#{i}"]
@endyear = params[:"endyear_#{i}"].to_s
@startdate = params[:"startdate_#{i}"]
@price = params[:"price_#{i}"]
@currency = params[:currency]

@startdate = Date.new(@startyear.to_i, @startmonth.to_i, @startday.to_i)
@enddate = Date.new(@endyear.to_i, @endmonth.to_i, @endday.to_i)

Further, if you don't need to use these variables in your view, there's no need to make them instance variables and you should make them local variables instead (i.e. drop the leading @ in the name).

like image 157
Andrew Marshall Avatar answered Nov 22 '22 01:11

Andrew Marshall