我有一个Event
模型,它有一个start_date
和end_date
。我有一个简单的验证,以确保在end_date
之后start_date
,但是,当日期字段未更改但另一个字段已更新时,验证仍然失败。在这种情况下,它解释字段为零,即使在跟踪中,记录显示正确的字段值。
# 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?) %>
即使我在跟踪参数中看到end_date
and填充,如果我在验证中添加(或 end_date),它也会在控制台中打印为 nil。start_date
put start_date
end_after_start