ruby on rails - Modifying ActiveRecord Validations with mixin -


i have activerecord mixin (i think can call that?) adds various default scopes , callbacks models purpose of scoping multi-tenant queries.

what i'd able modify existing uniqueness validations on model include scope. found can see validations using model.validators, naturally tried modify scope option so:

model.validators   .select{|v| v.is_a?(activerecord::validations::uniquenessvalidator)}   .map{|v| v.options[:scope] = :client_id } 

.. results in error runtimeerror: can't modify frozen hash, options hash. know how can go this? understand involve pretty hacky code.

if editing isn't possible maybe can override or catch or something?

edit - i've found this, i'm trying won't work in rails 3.2, think they've changed how validations stored? can me/give me pointers on how working in rails 3?

finally cracked it. key _validate_callbacks:

def scope_validators(foreign_key)   new_callback_chain = self._validate_callbacks.reject |callback|     callback.raw_filter.is_a?(activerecord::validations::uniquenessvalidator)   end   deleted = self._validate_callbacks - new_callback_chain   (self._validate_callbacks.clear << new_callback_chain).flatten!   deleted.each |c|     v = c.raw_filter     v.attributes.each |a|       validates_uniqueness_of *v.attributes, v.options.merge(scope: foreign_key)     end   end end 

works treat mixed in models.


Comments