我在db中有一个datetime列,当我向用户显示它时,我想将其转换为一个简单的日期.

我该怎么做?

def shown_date
  # to_date does not exist, but is what I am looking for
  self.date || self.exif_date_time_original.to_date 
end

推荐答案

DateTime#to_date确实存在于ActiveSupport中:

$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
    from (irb):1

>> require 'active_support/core_ext'
=> true

>> DateTime.new.to_date
=> Mon, 01 Jan -4712

Ruby-on-rails相关问答推荐

在ransackable_scopes中的作用域上创建activeadmin过滤器

Rails Routing:在具有自己的路由的名称空间下组织路由

仅当未在带有ENV[';Dyno';]的Heroku问题上运行时才初始化Sidekiq Cron

有什么办法能把这写清楚吗?

使用ImportMaps将HighLightJS添加到rails 7.1

Rails 6:强类型原始 SQL 查询返回数组类型

为 has_attached_file 等活动记录属性创建类方法

搭建脚手架时建立关系

Rails - 生产模式下的错误

可以在 Rails/ActiveRecord 中使用 NULL 指定唯一索引吗?

如何验证 ActiveRecord 中邮箱字段的格式?

使用回形针使用 Activeadmin Rails 上传文件

在 factory_girl 中填充与 children 的关联

我如何找出为什么我不能#destroy() 记录?

参数错误:范围主体需要可调用

Rails:带参数的 URL/路径

Rails:如何修复‘生产’环境缺少 secret_key_base

rake db:回滚不起作用?

从 Rails 控制器获取主机名

如何在 Rails 迁移中判断数据库类型?