Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice on "Dynamic" Model validation

I have a model named Calendar.

The validations that will be applied to it varies from the selections made by the user.

I know that I can use custom validation + conditional validation to do this, but doesn't look very clean to me.

I wonder if I can store it on a database column and pass it to a "generic" validator method.

What do you think?

Explaining further:

A user has a calendar.
Other users that have access to this calendar, can schedule appointments.

To schedule an appointment the app should validate according to the rules defined by the calendar's owner.

There are many combinations, so what I came to is:

Create custom validator classes to each of the possible validations and make then conditional.

class Calendar
  validate_allowed_in_hollydays :appointment_date if :allowedinhollydays?
  (tenths of other cases)
  ...
end

This works, but feels wrong.

I'm thinking about storing somewhere which rules should be applied to that calendar and then doing something like:

validate_stored_rules :appointment_date
like image 352
Alex Takitani Avatar asked Apr 12 '11 20:04

Alex Takitani


1 Answers

It seems a little backwards to save the data in the database and then validate it.

I think your initial thought of going with some custom validation is the best bet. validates_with looks like your best option. You could then create a separate class and build all the validation inside that to keep it separate from your main model.

class Person < ActiveRecord::Base
  validates_with GoodnessValidator
end

class GoodnessValidator < ActiveModel::Validator
  def validate
    if record.first_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end

Code lifted straight from the Rails Validation Guide

like image 120
Pete Avatar answered Oct 09 '22 23:10

Pete