[英]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. 我希望我的rails应用程序接受日期字段的日期,格式为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: 在我的模型中,我试图将日期转换为美国标准,我认为Rails将调用它的Date.parse方法是期望的:
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: 如果知道有用,则表单字段是Orders中的嵌套,并且Orders设置为:
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 因此,这些项目正在@ order.save / @ order.update_attributes上进行验证和保存/更新
Thank you! 谢谢!
It may be just a case of the due_at
value being nil. 可能只是
due_at
值为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. 在你的情况下,它是一个空字符串,但由于
accepts_nested_attributes_for
上的:reject_if
选项而被忽略,因此它仍为零。
>> 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!! 我在Ruby 1.8.7中遇到了完全相同的问题,我能解决它的唯一方法是分两步完成自我分配!!
xxx = Date.strptime(self.due_at,"%d/%m/%Y").to_time xxx = Date.strptime(self.due_at,“%d /%m /%Y”)。to_time
self.due_at = xxx 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.
我唯一能想到的是,ruby在完成使用右侧的due_at源字符串之前,逐个分配新目标日期类中的字段。
The problem does not seem to exist in Ruby 1.9.3 Ruby 1.9.3中似乎不存在这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.