关于“动态"的建议模型验证 [英] Advice on "Dynamic" Model validation

查看:35
本文介绍了关于“动态"的建议模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Calendar 的模型.

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.

你怎么看?

用户有一个日历.
有权访问此日历的其他用户可以安排约会.

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

推荐答案

感谢大家的帮助.

我的工作是这样的:

def after_initialize        
  singleton = class << self; self; end

  validations = eval(calendar.cofig)

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

这篇关于关于“动态"的建议模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆