简体   繁体   English

Ruby on Rails:如何在没有Active Record的情况下验证模型?

[英]Ruby on Rails: How to validate a model without Active Record?

I'm currently trying to validate fields without having an ActiveRecord::Base inheritance. 我目前正在尝试验证没有ActiveRecord::Base继承的字段。

My model stores the data on a cache server so I do not need ActiveRecord. 我的模型将数据存储在缓存服务器上,因此我不需要ActiveRecord。

Anyway, I would like to validate the fields of the model like I would if I was using ActiveRecord (eg validates_numericality_of :quantity, :greater_than => 0 ) ? 无论如何,我想验证模型的字段,就像我使用ActiveRecord一样(例如validates_numericality_of :quantity, :greater_than => 0 )?

How can I do that? 我怎样才能做到这一点?

Thank you very much for your help. 非常感谢您的帮助。

In Rails 3, Active Model contains the non-database functionality of Active Record. 在Rails 3中,Active Model包含Active Record的非数据库功能。

Basically, you need to include ActiveModel::Validations , define your fields as attr_accessor , use an initialize method to initialize the attributes and make them non-persisted as your model isn't persisted to a database. 基本上,您需要包含ActiveModel::Validations ,将您的字段定义为attr_accessor ,使用initialize方法初始化属性并使其不持久化,因为您的模型不会持久保存到数据库。

This way you can have validations on the tableless model and your controller the same as if you were using Active Record. 这样,您可以对无表格模型和控制器进行验证,就像使用Active Record一样。 There's also a Railscast on this http://railscasts.com/episodes/219-active-model . 这个http://railscasts.com/episodes/219-active-model上还有一个Railscast。

Check out our Veto gem instead if you're looking for a standalone validations for ruby objects. 如果您正在寻找红宝石对象的独立验证,请查看我们的Veto gem It's lightweight, and has no dependencies.. ActiveModel might be overkill. 它是轻量级的,没有依赖性.ActiveModel可能有点过分。

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

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