Last active
October 1, 2015 23:47
-
-
Save granolocks/2125273 to your computer and use it in GitHub Desktop.
Custom Rails Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/helpers/my_model_helper.rb | |
class MyModelValidator < ActiveModel::Validator | |
def validate(mymodel) | |
unless mymodel.starts_at.nil? || mymodel.ends_at.nil? | |
validate_times(mymodel) | |
end | |
end | |
def validate_times(mymodel) | |
unless mymodel.starts_at < mymodel.ends_at | |
event.errors[:end_date] << 'must be after start date' | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/my_model.rb | |
class MyModel < ActiveRecord::Base | |
include ActiveModel::Validations | |
validates_with MyModelValidator | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment