验证end_date晚于Rails 4中的start_date

时间:2015-11-10 21:19:36

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

我正在尝试确定验证end_date是否大于表单中start_date的最佳方法。

如果有人不小心选择了一个大于end_date的start_date,我就不知道如何抛出错误。

在我的表单中,如果事件只有一天,我可以提交一个日期(我使用javascript将start_date选择值复制到end_date选择值中),如果事件是,则使用start_date和end_date超过24小时。

屏幕截图中的以下场景应该触发表单的第3个错误。

screenshopt of form

这是表格的相关部分:

event_form.html.erb

<%= form_for(@event, html: { multipart: true }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="checkbox">
  <label>
    <%= f.check_box :single_day %> Is this a multi-day event?
  </label>
</div>
<div class="field">
  <%= f.label :start_date %><br />
  <%= f.date_select :start_date, :start_year => Date.current.year, :end_year => 1900  %>
</div>
<div id="end_date_div" class="field">
  <%= f.label :end_date %><br />
  <%= f.date_select :end_date, :start_year => Date.current.year, :end_year => 1900  %>
</div>
<%= f.submit "Post", class: "btn btn-primary", :id=>"event_submit" %>
<% end %>

event.rb

class Event < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :user_id, presence: true
  validates :title,   presence: true
  validates :content, presence: true
  validate  :picture_size

  private

    # Validates the size of an uploaded picture.
    def picture_size
      if picture.size > 5.megabytes
        errors.add(:picture, "should be less than 5MB")
      end
    end
end

events_controller.erb

class EventsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

  def create
    @event = current_user.events.build(event_params)
    if @event.save
      flash[:success] = "Event created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @event.destroy
    flash[:success] = "Event deleted"
    redirect_to request.referrer || root_url
  end

  private

    def event_params
        #may need to add the other variables here
      params.require(:event).permit(:title, :content, :single_day, :start_date, :end_date, :picture)
    end

    def correct_user
      @event = current_user.events.find_by(id: params[:id])
      redirect_to root_url if @event.nil?
    end
end

1 个答案:

答案 0 :(得分:9)

您正在寻找的是end_date字段上的另一个自定义验证。您可以在模型中编写如下内容:

validate :end_date_after_start_date?

def end_date_after_start_date?
  if end_date < start_date
    errors.add :end_date, "must be after start date"
  end
end

这会手动向模型添加错误,确保验证不成功。

有关自定义验证的更多信息: http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations