I want to do custom model validation, and after a bit of googling and
looking at the api, i found out that on Rails 3, you can use the
validate method by passing it a method symbol or a block.
class Comment
include ActiveModel::Validations
validate :must_be_friends
def must_be_friends
errors.add(:base, “Must be friends to leave a comment”) unless
commenter.friend_of?(commentee)
end
end
Now I’m using rails 2.3.8 and I couldn’t find this documented on the 2.3
api docs, yet when I use it on my code, it just magically works whether
i pass it a block or symbol. I tried looking at the source, but the only
thing i can see is a empty validate method that is left for user to
override. Any ideas on why it just works?
Without having looked at the Rails source code, I would think “validate”
is simply attaching a before_save filter to the model to the method
passed in as a symbol. All you have done here is basically specify a
before filter to a custom method.
Andrew S. wrote in post #1005186:
Without having looked at the Rails source code, I would think “validate”
is simply attaching a before_save filter to the model to the method
passed in as a symbol. All you have done here is basically specify a
before filter to a custom method.
Ic, I guess you’re right, on the ActiveRecord::Validations, validate is
defined as a callback as you suggested
module Validations
VALIDATIONS = %w( validate validate_on_create validate_on_update )
def self.included(base) # :nodoc:
base.extend ClassMethods
base.class_eval do
alias_method_chain :save, :validation
alias_method_chain :save!, :validation
end
base.send :include, ActiveSupport::Callbacks
base.define_callbacks *VALIDATIONS
end