Skip to content

Instantly share code, notes, and snippets.

@granolocks
Last active October 1, 2015 23:47
Show Gist options
  • Save granolocks/2125273 to your computer and use it in GitHub Desktop.
Save granolocks/2125273 to your computer and use it in GitHub Desktop.
Custom Rails Validator
# 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
# 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