在f.text_field中显示格式化日期(如果存在),否则显示占位符

时间:2014-09-24 12:36:56

标签: ruby-on-rails ruby-on-rails-4 date-format form-helpers

以下代码仅用于显示日期:

f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: @post.try(:published_at)

但我怎么格式化呢?

如果我知道日期存在,这就是我格式化的方式:

value: @post.published_at.strftime("%e %b %Y")

2 个答案:

答案 0 :(得分:1)

为什么不添加一个以首选格式返回日期的简单方法?

class YourModel
  def formatted_published_at
    published_at.strftime("%e %b %Y") if published_at?
  end
end

除了表单外,您可能也会在其他视图中使用它。

答案 1 :(得分:1)

围绕辅助函数换行以更改格式

f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: custom_format(@post.try(:published_at))

some_helper.rb

def custom_format(date)
  date ? date.strftime("%e %b %Y") : nil
end
相关问题