在 ruby 模型中设置日期格式 (sinatra/datamapper)
我有一个包含日期属性的 ruby 模型,我希望能够以 dd/MM/yyyy 格式作为参数传入。
但是,我的 sqlite3 数据库以 yyyy-MM-dd 格式存储数据,因此当传入像 20/10/2010 这样的日期时,它不会被读取到数据库中。
我正在使用 Sinatra 框架并使用 haml 进行标记创建。
我是否需要编写一个助手来获取日期字符串并将其转换为数据库的正确格式?或者我可以在 models 属性上设置格式类型吗?
谢谢。
I have a ruby model that contains a date attribue which I'd like to be able to pass in as a parameter in the format dd/MM/yyyy.
However, my sqlite3 db stores the data in yyyy-MM-dd format so when a date like 20/10/2010 gets passed in, it will not be read to the database.
I am using the Sinatra framework and using haml for the markup creation.
Do I need to write a helper that takes the date string and converts it to the correct format for the db? Or can I set a format type on the models attribute?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要担心数据库的日期内部表示; DataMapper 可以为您做到这一点。您只需确保向其传递有效的
Date
对象即可。查看 http://ruby-doc.org/core/classes/Date.html< /a> 用于
Date
类可用的方法。对于你的例子:You shouldn't need to worry about the database's internal representation of the date; DataMapper is there to do that for you. You just need to make sure you are passing it a valid
Date
object.Check out http://ruby-doc.org/core/classes/Date.html for methods available to the
Date
class. For your example:我不知道这是否有帮助,前段时间我遇到了同样的问题:我使用
Rack::Utils.escape_html(params[:datetime])
在用户输入上转义 html,如果我在表单字段中输入了一个日期,如“25/02/2013”,它将被发送到 DataMapper 模型,如下所示:16/02/2013
(带有转义的 html代码),所以它以错误的方式保存(日期最终是小时或类似的东西)。也许您也在以一种尴尬的方式使用“escape_html”方法?
I don't know if this can help, some time ago I had the same problem: I was using
Rack::Utils.escape_html(params[:datetime])
to escape html on user input and if I typed a date in a form field like this "25/02/2013" it would be sent to the DataMapper model like this:16/02/2013
(with escaped html codes) so it was saving it the wrong way (day ended up being the hour or something similar).Maybe you are also using "escape_html" method in an awkward way?