Wednesday, October 20, 2010

[Rails] Automatic validation

I want to automate a validation on all (or almost all) my models. That
validations should happen before every delete/destroy.

The goal is to stop the user from deleting a record if it has any
'has*' associations. I know that there are gems like
'acts_as_paranoid' that will keep the record in the DB while marking
it as 'deleted', but that is not what I need here.

I already have in a module the initial code that checks for
association records. The code is posted below for critique and in case
anybody is interested. The code might change, though, based on
requirements.

What I need is to know how to make all models run automatically the
method ('dependencies_found?' in the code below) whenever a record is
deleted without having to go to all models and include the module
manually.

Any ideas?

Thanks in advance.

<code>
module Dependable
def dependencies_found?
dependencies = self.class.reflect_on_all_associations.select {|a|
a.macro.to_s[0, 3] == 'has'}
dependencies.any? {|d| eval "!self.#{d.name}.blank?"}
end
end
</code>

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate