简体   繁体   中英

Getting rails to accept European date format (dd/mm/yyyy)

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!

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM