【问题标题】:Rails Console Showing Date Only for Datetime ColumnRails 控制台仅显示日期时间列的日期
【发布时间】:2016-10-21 23:56:27
【问题描述】:

我的Reminders 模型中有两列(datemail_date),列类型为datetime,您可以在我的schema.rb 中看到:

create_table "reminders", force: :cascade do |t|
    t.string   "name"
    t.datetime "date"
    t.boolean  "reminder",      default: false
    t.string   "repeating"
    t.boolean  "approved"
    t.boolean  "gift",          default: false
    t.boolean  "gift_help",     default: false
    t.string   "occasion_type", default: "Other"
    t.integer  "user_id"
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.string   "slug"
    t.datetime "mail_date"
  end

但是,在我的console 中,它们仅显示为日期:

[33] pry(main)> Reminder.where(name: "Mentor Call")
  Reminder Load (0.4ms)  SELECT "reminders".* FROM "reminders" WHERE "reminders"."name" = ?  [["name", "Mentor Call"]]
=> [#<Reminder:0x007fe32b13f090
  id: 8,
  name: "Mentor Call",
  date: Thu, 27 Oct 2016,
  reminder: true,
  repeating: "Weekly",
  approved: nil,
  gift: false,
  gift_help: false,
  occasion_type: "Other",
  user_id: 1,
  created_at: Thu, 13 Oct 2016 01:59:57 UTC +00:00,
  updated_at: Fri, 21 Oct 2016 23:47:16 UTC +00:00,
  slug: "mentor-call",
  mail_date: Thu, 27 Oct 2016>]

我知道datetime 数据正在保存,因为它显示在我的查看页面上,这里...

October 27, 2016 07:00  Mentor Call     ... 2016-10-27 07:00:00 UTC

...从这个erb生成:

<% @reminders.each do |o| %>
    <tr>
      <td>
        <%= o.date.try(:to_formatted_s, :long) %>
      </td>
      <td>
        <%= link_to reminder_path(o), style: "color: black" do %>
          <strong><%= o.name %></strong>
        <% end %>
        ...
      <td>
        <% if o.reminder %>
          <%= o.mail_date.try(:to_formatted_s, "%m/%d/%Y") %>
        <% else %>
          None, you're on your own.
        <% end %>
      </td>
    </tr>

我正在尝试创建一个在mail_date 上发送的mailer,但由于datetimedate 的这个问题,我遇到了麻烦(我认为)。谁能帮我解惑?

【问题讨论】:

  • 如果您将date 列称为其他名称,例如remind_on,会发生什么情况?
  • @mysmallidea,你辜负了你的用户名。这完全解决了它。如果你把它写成答案,我会很乐意选择它。

标签: ruby-on-rails


【解决方案1】:

我怀疑date 列的名称与Rails 或Ruby 的reserved words 存在冲突。将date 列的名称更改为其他名称,例如remind_at,这样就可以解决问题:

create_table "reminders", force: :cascade do |t|
  t.string   "name"
  t.datetime "remind_at"
  t.boolean  "reminder",      default: false
  # ...
end

【讨论】:

  • 作为一般约定,我喜欢使用以“_on”结尾的描述性名称作为日期,使用“_at”作为日期时间。所以我会使用mailed_at 而不是mail_date。如果我只想要日期(没有时间),我会称之为mailed_on。对我来说,当我(或其他开发人员)在数月或数年后阅读源代码时,这会更好地了解预期的返回值。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多