我正在尝试创建一个事件,该事件有一个日期和一个时间字段。在为
protest
创建表时,我没有添加时间字段,因此我必须运行迁移来添加时间字段。但我现在在创建表单时遇到问题。创建时间和日期字段的优雅解决方案是什么?
class CreateProtests < ActiveRecord::Migration[5.1]
def change
create_table :protests do |t|
t.string :name
t.text :description
t.string :location
t.datetime :starts_at
t.references :creator, index: true, foreign_key: { to_table: :users }
end
end
end
然后我添加了一个表示一天中时间的字段:
class AddStartsAtTimeOfDayToProtests < ActiveRecord::Migration[5.1]
def change
add_column :protests, :starts_at_time_of_day, :datetime
end
end
抗议/new.html.erb
<div class="col-md-12">
<div class="card">
<div class="card-header"><h2>Create A Protest</h2></div>
<div class="card-block">
<%= form_for(@protest, url: protests_path, html: {multipart: true}) do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :location %>
<%= f.text_field :location, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label "Date:" %>
<%= f.text_field :starts_at, value: "02/16/13", id: "dp2"%>
</div>
<div class="form-group">
<%= f.label "Time:" %>
<%= f.time_select :starts_at, ignore_date: true, class: "form-control"%>
</div>
<div class="form-group">
<%= f.label :image %>
<%= f.file_field :image, as: :file, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Create", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
日期和时间都捕获在单列中
:starts_at
,因此您不需要另一列来表示一天中的时间。
您的表格应该包含:
<div class="form-group">
<%= f.label "Starts At:" %>
<%= f.datetime_select :starts_at, class: "form-control"%>
</div>
这里是文档的链接: https://apidock.com/rails/ActionView/Helpers/FormBuilder/datetime_select
为日期添加
date_field
,为时间添加 time_field
,以具有如下两个字段。
<div class="form-group">
<%= f.label "Date:" %>
<%= f.date_field :starts_at, class: "form-control"%>
</div>
<div class="form-group">
<%= f.label "Time:" %>
<%= f.time_field :starts_at, class: "form-control"%>
</div>