Ruby on Rails:如何在没有 Active Record 的情况下验证模型? [英] Ruby on Rails: How to validate a model without Active Record?

查看:26
本文介绍了Ruby on Rails:如何在没有 Active Record 的情况下验证模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在没有 ActiveRecord::Base 继承的情况下验证字段.

我的模型将数据存储在缓存服务器上,因此我不需要 ActiveRecord.

无论如何,我想像使用 ActiveRecord 一样验证模型的字段(例如 validates_numericality_of :quantity, :greater_than => 0)?

我该怎么做?

非常感谢您的帮助.

解决方案

在 Rails 3 中,Active Model 包含 Active Record 的非数据库功能.

基本上,您需要包含 ActiveModel::Validations,将您的字段定义为 attr_accessor,使用 initialize 方法来初始化属性和使它们非持久化,因为您的模型没有持久化到数据库中.

通过这种方式,您可以像使用 Active Record 一样对无表模型和控制器进行验证.这个http://railscasts.com/episodes/219-active-model还有一个Railscast.>

I'm currently trying to validate fields without having an ActiveRecord::Base inheritance.

My model stores the data on a cache server so I do not need ActiveRecord.

Anyway, I would like to validate the fields of the model like I would if I was using ActiveRecord (e.g 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.

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.

This way you can have validations on the tableless model and your controller the same as if you were using Active Record. There's also a Railscast on this http://railscasts.com/episodes/219-active-model.

这篇关于Ruby on Rails:如何在没有 Active Record 的情况下验证模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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