views:

333

answers:

1

Hi,

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!

+1  A: 

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 on accepts_nested_attributes_for, and so it remains as nil.

>> Date.strptime(nil, "%d/%m/%Y")
TypeError: can't dup NilClass

Take care of it with some conditional then.

self.due_at = Date.strptime(self.due_at,"%d/%m/%Y").to_time unless self.due_at.nil?
htanata