简体   繁体   English

Ruby on Rails 4:使用数据库和表单之间的日期

[英]Ruby on Rails 4: Working with dates between database and forms

I am looking for some help with converting dates back and forth from a form and database. 我正在寻找一些从表单和数据库来回转换日期的帮助。 I have been using the following method, but it seems like there should be a better/easier way to manage this. 我一直在使用以下方法,但是似乎应该有一种更好/更简便的方法来管理此方法。

The code in the view: 视图中的代码:

  <%= f.label :issue_date, "Date Issued" %>
  <%= f.text_field :issue_date, class: 'form-control', :value => @license.issue_date.strftime("%m-%d-%Y") %>

The code in the controller: 控制器中的代码:

params[:license][:issue_date] = DateTime.strptime( params[:license][:issue_date], "%m-%d-%Y").strftime("%Y-%m-%d")
params[:license][:expiration_date] = DateTime.strptime( params[:license][:expiration_date], "%m-%d-%Y").strftime("%Y-%m-%d")

My concern is that this depends too much on the input format being correct. 我担心的是,这很大程度上取决于输入格式是否正确。 For instance, if the inputs 4/2/2015 instead of 4-2-2015, it breaks the code. 例如,如果输入4/2/2015而不是4-2-2015,它将破坏代码。 I would appreciate any help or advice! 我将不胜感激任何帮助或建议! I have been reading a lot of posts on dates, but nothing specific to answering this question. 我已经阅读了很多有关约会的文章,但没有专门回答这个问题。

Unfortunately, a date input with good UI is hard to set up in Rails, at least in my experience. 不幸的是,至少在我的经验中,很难在Rails中设置具有良好UI的日期输入。 If you are willing to compromise a bit on the UI, the simplest solution is to use the built-in date_select helper: 如果您愿意在UI上做出一些妥协,最简单的解决方案是使用内置的date_select帮助器:

<%= f.date_select :issue_date %>

This will generate three select inputs, like this: 这将生成三个选择输入,如下所示:

在此处输入图片说明

Rails will automatically handle translating the submission from these three inputs into a proper date in the database. Rails将自动处理将来自这三个输入的提交转换为数据库中的正确日期。 Again, the UI is not great, but it does solve the date format validation problem. 同样,UI并不是很好,但是它确实解决了日期格式验证问题。

Later, if you decide to use a Javascript date picker instead, set up the JS to ensure that the date value is always submitted to the server in YYYY-MM-DD format, which is what Rails expects. 以后,如果您决定改用Javascript日期选择器,则设置JS以确保日期值始终以YYYY-MM-DD格式提交到服务器,这正是Rails期望的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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