How to gracefully handle “Mysql2::Error: Invalid date” in ActiveRecord?

﹥>﹥吖頭↗ 提交于 2019-12-04 17:30:01

I had the same problem. The solution was to tell mysql2 not to perform casting, like this:

client.query(sql, cast: false).each do |row|
  row['some_date'] = Date.parse(row['some_date']) rescue(nil)
end

See mysql2 documentation for details on how to build client object. If required, access rails db config via ActiveRecord::Base.configurations.

Create a data import rake task that does all the conversions and fixes you need (including the data parsing and fixing), and run it every time you get a fresh update from the legacy app. The task can use raw SQL (look-up "execute" and "exec_query" methods), it doesn't have to work with models. This will be your magical "gem" that you were looking for. Obviously, you cannot have a one-fits-all tool for that, as every case of broken data is unique. But just don't create kludges in your new code base.

bartgras

Similar to: Rails: How to handle existing invalid dates in database? and also without correct answer so I repost my solution below.

I think the simplest solution that worked for me was to set in database.yml file write cast: false, e.g. for development section

development
  <<: *default
  adapter: mysql2    
  (... some other settings ...)
  cast: false

I believe it will solve your problem Date.parse()

e.g. Date.parse(foo.created_at)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!