ruby on rails 3 - DRYup shared model validations on before_destroy -


to prevent removal of related records, applying before_destroy callbacks approach on each model

i defined several related-records validation methods in module, can shared different models' before_destroy callbacks:

class teacher < activerecord::base   include relatedmodels   before_destroy :has_courses   ... end  class level < activerecord::base   include relatedmodels   before_destroy :has_courses   ... end  module relatedmodels    def has_courses     if self.courses.any?       self.errors[:base] << "you cannot delete while associated courses exists"       return false     end   end    def has_reports     if self.reports.any?       self.errors[:base] << "you cannot delete while associated reports exists"       return false     end   end    def has_students     if self.students.any?       self.errors[:base] << "you cannot delete while associated students exists"       return false     end   end    ...  end 

but doesn't looks dry

any idea how in single method? meta-programming it's not among skills

thanks in advance

you might want try observer class

these depreciated in rails 4 (you have use rails-observers gem), seem still part of rails 3 core


observer classes

"listen" specified actions in model, , provide extended functionality. stated documentation, particularly de-cluttering models, allowing combine lot of functionality 1 central set of functions

here's might want (please bare in mind have used these in rails 4):

class relatedobserver < activerecord::observer   observe :teachers, :school    def before_destroy(record)       associations = %w(teachers schools reports)       associations.each |association|           if record.send(association).any?               self.errors[:base] << "you cannot delete while associated #{association.pluralize} exists"               return false           end       end   end end 

here's good resource you


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -