yellowreign
yellowreign

Reputation: 3638

Rails Thinks Field is Nil When it Shouldn't

I have an Event model which has a start_date and end_date. I have a simple validation to make sure that the end_date is after the start_date, however, the validation keeps failing when a date field is not changed, but another field is updated. In such cases, it interprets the fields are nil, even though in the trace, the record shows the proper field values.

# error
undefined method `<' for nil:NilClass
app/models/event.rb:32:in `end_after_start'


# validation in event.rb
attr_accessible :end_date, :start_date    

validate :end_after_start

def end_after_start
  if end_date < start_date
    errors.add(:end_date, "must be after the start date")
  end    
end


# request parameters in trace
{"utf8"=>"✓",
  "_method"=>"put",
  "authenticity_token"=>"DD6rVimJxAJclO4IKfv69Txn8XkJZ4IpHZhh+cHOpg4=",
  "event"=>{"name"=>"Birthday",
  "start_date"=>"05/16/2013",
  "end_date"=>"05/31/2013", 
  "commit"=>"Submit",
  "id"=>"5"}


# _form     
<%= f.text_field :start_date, :value => (@event.start_date.strftime("%m/%d/%Y") if @event.start_date.present?) %>
<%= f.text_field :end_date, :value => (@event.end_date.strftime("%m/%d/%Y") if @event.end_date.present?) %>

Even though I see the end_date and start_date populated in the trace parameters, if I add put start_date (or end_date) in the end_after_start validation, it prints as nil to the console.

Upvotes: 1

Views: 104

Answers (3)

yellowreign
yellowreign

Reputation: 3638

I got this to work by installing the american_date gem. It allows for my date field to be displayed as MM/DD/YYYY and validates and saves my date correctly.

Upvotes: 0

Bernardo Mendes
Bernardo Mendes

Reputation: 1220

Try to set:

attr_accessor :end_date, :start_date

If you do not have the columns in your database, you will need that.

attr_accessible allows parameters in a mass association.

attr_accessor sets a getter and a setter.

If you have those columns you could try prepending self..

Upvotes: 0

Alex Peachey
Alex Peachey

Reputation: 4676

The problem is your form is formatting your dates as "mm/dd/yyyy" and the fields are being submitted to your application in that format as strings.

There is no implicit conversion of a string in that format to a DateTime so your start_date and end_date are ending up nil.

Upvotes: 1

Related Questions