I want my rails app to accept dates for a date field in the format dd/mm/yyyy.
In my model I have tried to convert the date to the American standard which I think the Date.parse method that Rails will call on it is expecting:
before_validation :check_due_at_format
def check_due_at_format
self.due_at = Date.strptime(self.due_at,"%d/%m/%Y").to_time
end
However, this returns:
TypeError in OrdersController#update
can't dup NilClass
If it is useful to know, the Items form fields are a nested for within Orders, and Orders are set to:
accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:quantity].blank? && a[:due_at].blank? }, :allow_destroy => :true
So the items are being validated and saved/updated on @order.save/@order.update_attributes
Thank you!
I have struck exactly the same problem in Ruby 1.8.7 and the only way that I could solve it was to do the self assignment in two steps!!
xxx = Date.strptime(self.due_at,"%d/%m/%Y").to_time
self.due_at = xxx
I can' believe that this should be necessary. The only thing I can think of is that ruby is assigning fields in the new target date class on a piecemeal basis before it has finished using the due_at source string on the right hand side.
The problem does not seem to exist in Ruby 1.9.3
It may be just a case of the
due_at
value being nil. In your case it's an empty string, but ignored because of the:reject_if
option onaccepts_nested_attributes_for
, and so it remains as nil.Take care of it with some conditional then.