【问题标题】:Date fields and textinput in railsRails 中的日期字段和文本输入
【发布时间】:2011-12-28 19:49:52
【问题描述】:

我有一个迁移:

  def change
    create_table :tasks do |t|
      t.date :date, :null => false
    end
  end

还有一个观点:

<%= form_for @task do |f| %>
<%= f.text_field :date %>
<% end %>

问题是

  1. 为什么对于数据库中已有的记录,我使用“2011-12-23 00:00:00”而不是“2011-12-23”?在数据库中,它们的格式为“2011-12-23”。

  2. 如何将日期内部化,这样我就可以拥有像“12.23.11”这样的日期。

【问题讨论】:

  • 您使用的是什么数据库?我确实执行了these commands,设置了root :to =&gt; tasks#index,然后创建了一个新任务,一切都按预期工作(即没有尾随00:00:00)。

标签: ruby-on-rails-3 activerecord internationalization


【解决方案1】:

我猜你可以使用 value 选项和 i18n API/l 助手。类似的东西:

<%= f.text_field :date, :value => l(@model.date) %>

然后在您的语言环境文件中:

# config/locales/your_locale.yml
your_locale:
  date:
    formats:
      # Whatever format that fits your needs
      default: "%d/%m%/%Y"

【讨论】:

    【解决方案2】:

    制作一个可以获取价值并吐出更好的东西的助手

    def prettifydate(ugly)
       return ugly.strftime('%m.%d.%Y')
    end
    

    在您的表单中,将值作为辅助方法并返回漂亮的字符串。

    <%= form_for @task do |f| %>
       <%= f.text_field :date, :value => prettifydate(@task.date) %>
    <% end %>
    

    【讨论】:

    • 这里有两个问题。首先,rails 已经有自己的类似这个助手的东西,所以再做一个不是一个好主意。其次,在 Rails 中使用 i18n 引擎并不好。
    猜你喜欢
    • 1970-01-01
    • 2016-11-10
    • 2017-08-15
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多