Rails:如何在DB中保存时间时指定日期

时间:2016-04-02 23:06:06

标签: ruby-on-rails ruby date ruby-on-rails-4

今天的日期是在我将时间保存在数据库中时设置的。

例如,我在视图中设置时间如下;

from: 8:00 to : 9:30

这些时间保存如下;

2016-04-03 08:00:00.000000 2016-04-03 09:30:00.000000 (今天是2016-04-03)

我想做的是将日期设定为指定日期。

我在同一视图中有depature date

如果我为2016-05-12选择depature date,我想像这样保存;

2016-05-12 08:00:00.000000 2016-05-12 09:30:00.000000

我使用bootstrap3-datetimepicker-rails选择depature date

schema.rb

...
create_table "events", force: :cascade do |t|
  t.time     "from"
  t.time     "to"
...

_schedule_form.html.erb

<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<br>
  <%= f.label :departure_date %>
  <div class="input-group date" id="datetimepicker">
    <%= f.text_field :departure_date, :value => (f.object.departure_date.strftime('%b/%d/%Y') if f.object.departure_date), class: 'form-control' %>
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
  </div>
  <script type="text/javascript">
    $(function () {
      $('#datetimepicker').datetimepicker({format:'MMM-DD-YYYY'});
    });
  </script>
  <br>
  <div id="room">
    <%= f.simple_fields_for :rooms do |a| %>
    <div id="room_<%= a.object.object_id %>">
      <p class="day-number-element-selector"><b>Day&nbsp;<%= a.index.to_i + 1 %></b></p>

      <%= a.simple_fields_for :events do |e| %>
        <span class="form-inline">
          <p>
            <%= e.input :from, label: false %>
            <%= e.input :to, label: false %>
          </p>
        </span>
        <%= e.input :title, label: false %>
      <% end %>
    </div>

    <%= a.link_to_add "Add event", :events, data: {target: "#room_#{a.object.object_id}"}, class: "btn btn-primary" %>

    <%= a.input :room %>

    <% end %>
  </div>

如果你能给我如何设置,我将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以使用 before_save 回调,如下所示:

class Event < ActiveRecord::Base
  before_save :assign_date

  private

  def assign_date
    assign_specific_date(to)
    assign_specific_date(from)
  end

  def assign_specific_date(date)
    date.month = departure_date.month
    date.year  = departure_date.year
    date.day   = departure_date.day
  end
end

免责声明:我在这里肯定缺少协会,但这可以让您了解如何实施所需的协议。