views:

109

answers:

1

I'm trying to figure out whether I can call the validate method twice in an ActiveRecord model definition. Once, of course, would be in a mixin.

So the first question is, is it okay to put this method in a mixin:

  validate :check_them_dates

and not worry if classes that include me will want to call validate as well?

I have already looked at the Rails API and the method looks like this (in vaidations.rb):

  def validate #:doc:
  end

which is to say, where would I look for this?

+2  A: 

You can call validate in the model as many times as you want, so you don't have to worry about adding it to a mixin.

class Item < ActiveRecord::Base
  validate :check_them_dates
  validate :name_is_proper
end

If you are doing a mixin it is sometimes cleaner to use a block on the validate method. This way you don't have to worry about adding another method.

module ValidateThemDates
  def self.included(base)
    base.validate do |model|
      model.errors.add # ...
    end
  end
end

class Item < ActiveRecord::Base
  include ValidateThemDates
end

Good luck!

ryanb
Interesting. I had to stare at your code for a minute to figure out what's going on, but yes, that's perfect. I find the valid :method_name to be easier to understand, but I guess I need to use blocks more.
Yar
Oh, and thanks and +1 and best answer and all that!
Yar