10

I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.

views/dinners/new.html.erb:

<%= f.text_field :date,  id: "datepicker" %>  

models/dinner.rb:

attr_accessible :date
validates_presence_of :date

dinners_controller.rb:

def create
  @dinner = Dinner.new params[:dinner]
  if @dinner.save
    flash[:notice] = "Dinner created successfully."
    redirect_to controller: 'dinners'
  else
    flash.now[:alert] = @dinner.errors.full_messages.join("<br>").html_safe
    render action: "new"
  end
end

Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?

LonelyWebCrawler
  • 2,866
  • 4
  • 37
  • 57
  • 1
    Usually when something like this happens, I find it's a parameter that's not passed the way it should be. Check the server log. Is the :date parameter getting passed at all? If so, is it formatted correctly? Try logging out the `@dinner` object before you try to save it, see if it has a date set. – MrTheWalrus Jan 23 '13 at 19:56
  • Another thing to investigate in cases like this, is how it behaves on the rails console. When you do `d= Dinner.new(:date => "31/12/2012")` does `d.errors` show the same "can't be blank"? – berkes Jan 23 '13 at 19:58
  • Thanks for the tips. `@dinner` never has `date` set when I log it out, but trying it over the console works fine. – LonelyWebCrawler Jan 23 '13 at 20:00
  • Definitely something wrong with the parameter passing, then. Try logging out `params` during the action (or just look at the server log). That should tell you whether the date isn't getting passed at all, or if it's a problem with the format it's sent in. – MrTheWalrus Jan 23 '13 at 20:03
  • Just checked. Strangely, the date _is_ set in the POST request. – LonelyWebCrawler Jan 23 '13 at 20:06

1 Answers1

6

I've found the answer.

My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.

I chose the easy solution and changed the default date of datepicker, as shown here.

Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.

Community
  • 1
  • 1
LonelyWebCrawler
  • 2,866
  • 4
  • 37
  • 57