Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails field "can't be blank", even though it's not blank

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?

like image 867
LonelyWebCrawler Avatar asked Jan 23 '13 19:01

LonelyWebCrawler


1 Answers

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'.

like image 150
LonelyWebCrawler Avatar answered Sep 27 '22 19:09

LonelyWebCrawler