Reputation: 861
Today's date is set when I save the time in the DB.
For example, I set the time in the view as followings;
from: 8:00
to : 9:30
these times are saved as follows;
2016-04-03 08:00:00.000000
2016-04-03 09:30:00.000000
(today is 2016-04-03)
What I'd like to do is to set the date to the designated date.
I have depature date
in the same view.
If I choose 2016-05-12
for depature date
, I'd like to save like this;
2016-05-12 08:00:00.000000
2016-05-12 09:30:00.000000
I use bootstrap3-datetimepicker-rails
to select 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 <%= 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>
It would be appreciated if you could give me how to set.
Upvotes: 0
Views: 66
Reputation: 672
You could use a before_save callback, something like this:
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
Disclaimer: I'm definitely missing associations here, but this should give you an idea on how to implement what you need.
Upvotes: 2