19
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでdatetime型の前後入力のバリデーションをかける方法

Last updated at Posted at 2017-04-28

開始日と終了日があって、終了日が開始日よりも前の日付になったらダメだよってときのやつ。

やり方は簡単

・モデルにvalidationを作っちゃう
・以下参照

Eventモデルで実験

class Event < ActiveRecord::Base
  validates :start_date, presence: true
  validates :end_date, presence: true
  validate :start_end_check

  def start_end_check
    errors.add(:end_date, "の日付を正しく記入してください。") unless
    self.start_date < self.end_date
  end
end

ちゃんと動きました!いぇい!

参考元

「一言多いプログラマーの独り言」さん
http://programmer-jobs.blogspot.jp/2013/05/ruby-on-rails_21.html
助かりました。ありがとうございます。

19
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?