简体   繁体   English

通过ActiveSupport ::关注或自定义验证进行Rails动态模型验证

[英]Rails Dynamic Model Validations via ActiveSupport::Concern or Custom Validation

SO... 所以...

I am currently working on a rails project that will result in several models being created with similar fee attributes. 我目前正在研究Rails项目,该项目将导致创建具有相似费用属性的多个模型。 What I would like to do is create a re-usable validation mechanism. 我想做的是创建一个可重用的验证机制。 For example, my model could be.. 例如,我的模型可能是

Foo
  currency
  producer_product_fee
  producer_transport_fee
  consumer_product_fee
  consumer_transport_fee

...and I will have several models of a similar structure (always having two different sides to every fee) and I would like to validate that the fees are non-negative, valid numbers, and that the producer fee is always less than the corresponding consumer fee. ...而且我将有几种结构相似的模型(每种费用总是有两个不同的方面),我想证明这些费用是非负的有效数字,并且生产者费用始终小于相应的消费者费用。 Note that the different attributes across models may be named completely different, but it can be assumed that the pair of producer / consumer fees always are named the same, except the prefix. 请注意,跨模型的不同属性可能被命名为完全不同,但是可以假定,生产者/消费者费用对始终被命名为相同的前缀前缀。 Any tips on how to achieve this would be great. 关于如何实现这一目标的任何技巧都将是很棒的。

Something like this perhaps? 大概是这样吗?

validates_numericality_of :producer_product_fee, 
    less_than: Proc.new { |r| r.consumer_product_fee }, 
    greater_than_or_equal_to: 0,
    allow_blank: false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM