Getting rails to accept European date format (dd/m

2019-02-24 11:15发布

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!

2条回答
贪生不怕死
2楼-- · 2019-02-24 11:23

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

查看更多
叼着烟拽天下
3楼-- · 2019-02-24 11:41

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?
查看更多
登录 后发表回答