Rails:如何比较时间和显示错误?

时间:2016-04-02 23:58:09

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

我想查看fromto次。 如果from> to,我想显示错误。

如何编辑我的代码?

Althogh我尝试使用coverinclude的一些代码,我无法将它们应用到我的代码中。

schema.rb

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

schedules_controller.rb

...
  def new
    @schedule = Schedule.new
    room = @schedule.rooms.build
    schedule.events.build
  end

  def create
    @schedule = current_user.schedules.build(schedule_params)
    if @schedule.save
      flash[:success] = "schedule created!"
      redirect_to root_url
    else
      render 'new'
    end
  end

  def edit
    @day_max = Room.where("schedule_id = ?", @schedule.id).maximum(:day)
  end

  def update
    @schedule.rooms.maximum(:day)
    if @schedule.update(schedule_params)
      flash[:success] = "schedule updated!"
      redirect_to root_url
    else
      render 'edit'
    end
  end

_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 :(得分:1)

您可能希望在事件模型中实现验证器,如documentation中所述。

class Event < ActiveRecord::Base
  validates :to, presence: true
  validates :from, presence: true
  validate do |e|
    if e.from.present? && e.to.present? and e.from > e.to
      e.errors[:base] << "To time must be after from time"
    end
  end
end