在rails迁移中添加日期和时间字段

时间:2018-01-18 03:40:36

标签: ruby-on-rails rails-activerecord rails-migrations

我正在尝试创建一个事件,该事件有一个日期和一个时间字段。为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>

2 个答案:

答案 0 :(得分:0)

日期和时间都在单列: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

答案 1 :(得分:0)

为日期添加// polyfill if you don't have it Array.prototype.flatMap = function (f) { return this.reduce ((acc, x) => acc.concat (f (x)), []) } // your data const routes = [ { name : "userManagement" , childRoutes : [ { name : "blogManagement" , childRoutes : [ { name : "blog" , menu : { role : 1020 } } ] } , { name : "organizationList" , menu : { role : 1004 } } ] } , { name : "test" , menu : { role : 4667 } } ] // flat-mapped routes const allChildRoutes = routes.flatMap (function loop (node) { if (node.childRoutes) return node.childRoutes.flatMap (loop) else return [node] }) console.log (allChildRoutes),并为date_field添加以下两个字段的时间。

time_field