Reputation: 557
I have an application where I want to store all the database validation rules in the database because the admin needs to be able to change the validation rules from a GUI. Also the rules are expected to change frequently, so my requirement is that the rules need to be in the database.
For simplicity, let's just say I have a User model and "name" needs the validation rule of being present. Normally, you would say:
class User < ActiveRecord::Base
validates :name, presence: true
end
Is there any way to stick this rule in a Rule table, query the database for the rule, then have the model validate based off the rule in the Rule table? i.e. an easy way to write the query in the model file like this?
class User < ActiveRecord::Base
Rule.first.validation
end
Where the value of Rule.first.validation would be "validates :name, presence: true".
Thanks.
Upvotes: 3
Views: 522
Reputation: 126
Review this gem https://github.com/vprokopchuk256/mv-core. It allows you to define validations on database level. Something like this:
def change
create_table :posts do |t|
t.string :title, length: [1..30]
end
end
As result, either trigger or check validation will be created. That depends on the database.
Internally all validations are stored in the special :migration_validators table. :table_name, :column_name, :validation_type and validation options are stored there.
And there is possibility to level up validations from that table to you model:
class Post < ActiveRecord::Base
enforce_migration_validations
end
So - you can update :migration_validations table in order to dynamically add / remove validations. Structure of that table is quite trivial.
Upvotes: 0
Reputation: 11436
It's possible to do (say using validates
and eval
), but very limited and risky. Plus you're moving validation from where it's testable and deployed as working to the database where it's subject to the whims of your sysadmin. I'd strongly recommend against going against convention in this manner. You're better off rolling out frequent updates (with corresponding tests) in the long run.
Upvotes: 1