开发者

custom validation, included in a module, will not load

开发者 https://www.devze.com 2023-01-15 00:00 出处:网络
I am trying to include a custom validation across many models through a module, and I\'m seeing some strange behavior. I wrote a custom validation called validates_as_unique which checks to see if a g

I am trying to include a custom validation across many models through a module, and I'm seeing some strange behavior. I wrote a custom validation called validates_as_unique which checks to see if a group of attributes is unique among records in the database. In a module called FactBehaviors I have:

module FactBehaviors
  def self.included(base)
    base.class_eval do
      def self.acts_as_fact
        extend ClassMethods
        include InstanceMethods
      end
    end
  end

  module ClassMethods
    ...
  end

  module InstanceMethods
    def self.included(base)
      if base.respond_to?(:validate_as_unique)
        base.send(:validates_as_unique)
      end
    end
    ...
  end
end

The strangeness beings when I fire up the console and create a new, valid record (of type fact) then create another identical record. The validation passes (doesn't work properly). However, if I do reload! and try to create the same record again, the validation开发者_运维技巧 works and forbids me from creating the identical record.

I'm still a little murky as to the way rails loads classes, but I get the sense that that ignorance may be the problem here. Thoughts?


You'll have to extend ActiveRecord to add this module:

ActiveRecord::Base.extend(FactBehaviors)

to use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消