# Dynamic model validation

**URL:** <https://www.ruby-forum.com/t/dynamic-model-validation/205911>\
**Category:** Rails\
**Created:** [April 18, 2011, 4:54pm UTC](https://www.ruby-forum.com/t/dynamic-model-validation/205911 "2011-04-18T16:54:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![luislavena](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/0ea827/32.png) [@luislavena](https://www.ruby-forum.com/u/luislavena)\
**Post date:** [April 18, 2011, 4:54pm UTC](https://www.ruby-forum.com/t/dynamic-model-validation/205911/1 "2011-04-18T16:54:35Z")

</div>

Hi, I am searching for a way to dynamic validate my models.

The solution that I got working is:

def after\_initialize  
singleton = class \<\< self; self; end

validations = eval(calendar.cofig)

validations.each do |val|  
singleton.class\_eval(val)  
end  
end

On my actual app, I have 2 models

class Calendar \< ActiveRecord::Base  
has\_many :events  
end

class Event \< ActiveRecord::Base  
belongs\_to :calendar

def after\_initialize  
singleton = class \<\< self; self; end

```
validations = eval(calendar.config)

validations.each do |val|
   singleton.class_eval(val)
end

```

end

end

As you can see, the validation code that should be added to the Event  
class lies on the Calendar field “config”.

Works fine for a existing Event, but doesn’t for a new record. That’s  
because, at the time that after\_initialize is called, the association  
doesn’t exists yet.

I can’t find a way to do that besides putting the config values on  
Event itself.

Any advices?

Tks!
