开发者

Handling different date formats in ROR

I am trying to build a ROR app that allows users to enter date in various formats such as 12/31/11 (month/day/year) or 31/12/11 (day/month/year). In order to interpret date format, I will have a select field from where user can select the format of date. I can use Date.strptime(value,开发者_如何学Python format).to_s() in controller before saving record.

However, I am not sure is controller right place to put this information. Is there a way I can push this to model..say in before save method.


You could just save the data as it is (in the controller), and have another field in the model telling it how to interpret the data. Then, in a before_validation callback, you could try parsing the date according to the given format and writing it to the same field, now as a date. Problems may arise on the way back. Then, to display it in the view again, you could write helpers - but better yet, provide a method in the model (for instance, formatted_date) that will compute and display the date.

However, this requirement sounds strange. Why is the user's responsibility to select a date format? Shouldn't it be based on the user locale?

In any case, I suggest you register your date formats in an initializer, rather than repeting the format strings throughout the application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜