Fossmo
Fossmo

Reputation: 2892

ArgumentError (invalid date) in Ruby On Rails

I'm getting this ArgumentError (invalid date) error and can't figure out what's causing it. The method is called from javascript.

  def loadDay
     @first_day_of_week = Date.strptime("{ params[:year].to_s, :params[:month].to_s, params[:day].to_s }", "{ %Y, %m, %d }")

     ...
  end

The log looks like this:

  Started GET "/planner/loadDay?day=7&month=5&year=2011" for 127.0.0.1 at 2011-05-15 10:19:43 +0200
  Processing by PlannerController#loadDay as */*
  Parameters: {"day"=>"7", "month"=>"5", "year"=>"2011"}
  Completed   in 1ms

Please point me in the right direction.

Upvotes: 1

Views: 3497

Answers (1)

mu is too short
mu is too short

Reputation: 434585

You're missing a few #{} for string interpolation in the first argument to Date.strptime. I think you mean to say this:

Date.strptime("{ #{params[:year]}, #{params[:month]}, #{params[:day]} }", "{ %Y, %m, %d }")

Your call was just passing this literal string to strptime:

"{ params[:year].to_s, :params[:month].to_s, params[:day].to_s }"

and, without the values from params substituted in, strptime didn't know what you were talking, got upset, and raised an ArgumentError exception to indicate an "invalid date".

And you don't need the to_s calls inside #{} as #{} does that for you and the values in params will be strings anyway (unless, of course, you're doing some extra processing of params beyond what Rails normally does).

Upvotes: 2

Related Questions