In the book 'The Rails Way', Obie F. discusses keeping active- record validation code within a database and then applying those validations conditionally based upon certain attributes of the model. I had a similar requirement recently, before reading the book and ended up writing my own hand-rolled validator. This was quite painful and not as powerful as the built in ActiveRecord validations. Does any one have any info/links to posts etc that would give me a headstart on how to achieve conditional AR validations with the validation code stored in a database?
on 2009-04-17 05:01
on 2009-04-17 20:52
I think perhaps I have not phrased this very well, and that explains the lack of replies. I have a number of ActiveRecord models all based around an 'Order Model', a shortened version of which is shown below. class Order < ActiveRecord::Base has_many: previous_addresses has_one: applicant has_one: current_address end All of the other models belong to order. I wish to validate the various models such as applicant, current_address etc differently based upon the company attribute of the order. I have developed a solution to this which involved a complete hand- rolled validation suite, supporting all of the standard activeRecord validators. This solution was developed with a number of tables such as model, fields, field_items etc that described the validation and amounts to quite a lot of data. I now have to manipulate this data and copy and edit it for each new company that I am connecting to. This is tedious and error prone. Whilst reading 'The Rails Way', I found a section where Obie F. described keeping the validation code in the database in the form of ActiveRecord validation statements and injecting these into the models at runtime based upon the value of the company id. I am imagining keeping data in tables such as the following :- company: 200 model: person Code validates_length_of :middle_name, :maximum => 20, :allow_nil => true company: 201 model: person Code validates_length_of :middle_name, :maximum => 1, :allow_nil => true So for company 201 a middle name of 'John' would fail validation but that would be ok for company 200. Has anyone seen this done, and if so do they have any tips/suggestions on how to do it, even better does anyone have any links to tutorials/ code that does this?
on 2009-04-18 01:54
On Friday 17 April 2009, sweet61 wrote: > I am imagining keeping data in tables such as the following :- You know that you can call the ordinary validates_... methods from another method? class Company < ActiveRecord::Base include DatabaseValidator end module DatabaseValidator def self.included(base) <read validation specs from db>.each do |vmethod, options| base.send(vmethod, options) end end end You could store the validation method simply as the method name and the options as a YAML serialized hash. Michael -- Michael S. mailto:firstname.lastname@example.org http://www.schuerig.de/michael/