Ruby on rails 在f.text_字段中显示格式化日期(如果存在),否则显示占位符
以下代码仅在日期存在时才显示日期:Ruby on rails 在f.text_字段中显示格式化日期(如果存在),否则显示占位符,ruby-on-rails,ruby-on-rails-4,date-format,form-helpers,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") 但是我该如何格式化它呢 如果我知道日期已经存在,我会这样格式化它: f.text_field :published_at, placeholder: "E.g. 12 Sep 20
f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: @post.try(:published_at)
value: @post.published_at.strftime("%e %b %Y")
但是我该如何格式化它呢
如果我知道日期已经存在,我会这样格式化它:
f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: @post.try(:published_at)
value: @post.published_at.strftime("%e %b %Y")
为什么不添加一个简单的方法,以您喜欢的格式返回日期
class YourModel
def formatted_published_at
published_at.strftime("%e %b %Y") if published_at?
end
end
除了表单之外,您可能还会在其他视图中使用它。将其环绕在辅助函数周围以更改格式
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
你是关于@post.try(:published_at)。try(:strftime,“%e%b%Y”)
?