【问题标题】:Can Rails automatically parse datetime received from form text_fieldRails 可以自动解析从表单 text_field 收到的日期时间吗
【发布时间】:2010-09-28 04:45:19
【问题描述】:

Rails 可以自动解析从表单的 text_field 接收到的日期时间吗?

# in view
<div class="field">
  <%= f.label :created_at %><br />
  <%= f.textfield :created_at %>
</div>

# in controller
params[:product][:updated_at].yesterday

目前我收到以下错误:

undefined method `yesterday' for "2010-04-28 03:37:00 UTC":String

【问题讨论】:

  • 请向我们展示您当前的代码。
  • +1 表示@ryan 的请求。如果没有任何实际代码,将很难为您提供帮助

标签: ruby-on-rails json


【解决方案1】:

如果您将该参数直接放入模型中,就像 rails 生成器样板代码所做的那样,ActiveRecord 会为您处理这些问题

def create
    @product = Product.new(params[:product])
    @product.updated_at.yesterday #will succeed
    #rest of method
end

除此之外,您还遇到以下问题:

DateTime.parse(params[:product][:update_at])

DateTime.civil_from_format(:local, year, month, day, hour, minutes, seconds)

但是,根据我的经验,.civil_from_format 在夏令时无法正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多