获得欧洲日期格式(dd / mm / yyyy) [英] Getting rails to accept European date format (dd/mm/yyyy)

查看:1828
本文介绍了获得欧洲日期格式(dd / mm / yyyy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的模型中,我尝试将日期转换为我认为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

然而,这返回:

  TypeError在OrdersController#update 
不能dup NilClass

如果知道有用,项目表单字段在订单中嵌套,订单设置为:

  acceptable_nested_attributes_for:items,:reject_if => lambda {| a | a [:quantity] .blank? &&&一个[:due_at] .blank? },:allow_destroy => :true 

所以这些项目在@ order.save / @订单上被验证并保存/更新。 update_attributes



谢谢!

解决方案

可能只是一个例子的 due_at 值为零。在你的情况下,这是一个空字符串,但是由于 acceptance_nested_attributes_for 上的:reject_if 选项被忽略,所以它仍然是

 >> Date.strptime(nil,%d /%m /%Y)
TypeError:不能重复NilClass

然后用一些条件来处理它。

  self.due_at = Date.strptime(self。 due_at,%d /%m /%Y)。to_time除非self.due_at.nil? 


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?

这篇关于获得欧洲日期格式(dd / mm / yyyy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆