f.date_selectの validatesで今日より10日以上2年未満とするにはどうしたら良いでしょうか
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答1件
0
ベストアンサー
ActiveModel::Validator
を継承したクラスでバリデーションメソッドを実装し、それをモデル側でvalidates_with
を使用して呼び出す、という方法があるようです
適当なディレクトリにプロジェクトを作成して
lang
1rails --version # => Rails 4.2.0 2rails g model User birthday:date 3rake db:migrate
から始めてみました
spec/models/user_spec.rb
: テストは書き慣れていないためツッコミどころはあるとおもいます
(日付の範囲を制限するのに誕生日を想定・設定するというのもおかしいですね...)
lang
1require 'rails_helper' 2 3RSpec.describe User, :type => :model do 4 describe "date validate" do 5 before do 6 @user = User.new 7 Timecop.freeze(Date.current.change(year: 2014, month: 12, day: 31)) 8 end 9 10 subject { @user } 11 12 it "valid: after 10 days from the current date" do 13 @user.birthday = Date.current.advance(days: 10) 14 expect(@user).to be_valid 15 end 16 17 it "valid: within 2 years after the current date" do 18 @user.birthday = Date.current.advance(years: 2) 19 expect(@user).to be_valid 20 end 21 22 it 'invalid: after 9 days from current date' do 23 @user.birthday = Date.current.advance(days: 9) 24 expect(@user).to_not be_valid 25 end 26 27 it 'invalid: 2 years later from the current date' do 28 @user.birthday = Date.current.advance(years: 2, days: 1) 29 expect(@user).to_not be_valid 30 end 31 32 after { Timecop.return } 33 end 34end
app/models/user.rb
lang
1class DateRangeValidator < ActiveModel::Validator 2 def validate(record) 3 error_message = 'Date is not in a valid date range' 4 record.errors[:base] << error_message if valid_dates.exclude? record.birthday 5 end 6 7 def valid_dates 8 after = Date.current.advance(days: 10) 9 before = Date.current.advance(years: 2) 10 (after..before) 11 end 12end 13 14class User < ActiveRecord::Base 15 validates_with DateRangeValidator 16end
Links
-
Active Support Core Extensions / time — Ruby on Rails Guides
-
Active Record Validations / validates-with — Ruby on Rails Guides
validates_timelines gem を利用するほうが簡単なのかもしれません
投稿2015/01/07 04:39
総合スコア2321
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/01/07 04:51
2015/01/07 09:29