rails自定义验证_快速了解Rails定制验证

rails自定义验证

by Raymond Blessed

雷蒙德·福瑞斯(Raymond Blessed)

快速了解Rails定制验证 (A quick look at Rails Custom Validation)

I recently started working with Ruby (almost 2 months now) and Ruby on Rails (a little over 3 weeks). Working with Rails’ Active Record framework is one of my favorite things about Ruby on Rails. In this post, we will be looking at validations in Active Record, custom ones particularly. Here is a quick intro to Active Record before we move to the good stuff.

我最近开始使用Ruby(现在将近2个月)和Ruby on Rails(仅3个多星期)进行工作。 使用Rails的Active Record框架是我在Ruby on Rails上最喜欢的事情之一。 在本文中,我们将研究Active Record中的验证,尤其是自定义验证。 这是Active Record的快速介绍,然后我们介绍一些好东西。

Active Record is one of the core gems that make up Ruby on Rails. It is the part of the framework that deals with databases.

Active Record是构成Ruby on Rails的核心要素之一。 它是处理数据库的框架的一部分。

It is an ORM (Object Relational Mapping) framework that lets you build a schema for a database using pure ruby and it is based on the Active Record design pattern described by Martin Fowler. So, with Active Records, you are creating your DB, creating tables, storing, retrieving and deleting data using ruby which translates to SQL under the hood.

它是一个ORM(对象关系映射)框架,可让您使用纯Ruby为数据库构建模式,它基于Martin Fowler描述的Active Record设计模式。 因此,使用Active Records,您可以使用ruby创建数据库,创建表,存储,检索和删除数据,而ruby则可以转换为SQL。

快速介绍 (Quick Intro)

Suppose we have a student model with properties first name and last name. To use Active Record we just need to extend the ApplicationRecord and when we run rails db:migrate it gives us the SQL statement for it.

假设我们有一个学生模型,其属性为名字和姓氏。 要使用Active Record,我们只需要扩展ApplicationRecord并在运行rails db:migrate为其提供SQL语句。

To interact with the database, we use methods inherited from the ApplicationRecord superclass.

为了与数据库交互,我们使用从ApplicationRecord超类继承的方法。

It also supports associations and other database stuff.

它还支持关联和其他数据库内容。

For a detailed intro to Active Record, check out the official ruby on rails guide.

有关Active Record的详细介绍,请查看Rails官方指南。

验证方式 (Validation)

Because we write web applications for users other than ourselves, we cannot be sure that the users will always input valid data into the database. To enforce this, Active Record provides us a mini-validation framework that ensures the presence of data, uniqueness of certain fields, and so on.

因为我们为自己以外的用户编写Web应用程序,所以我们不能确保用户将始终将有效数据输入数据库。 为了执行此操作,Active Record为我们提供了一个迷你验证框架,该框架可确保数据的存在,某些字段的唯一性等。

Let’s look at our students table above. We wouldn’t want to create a user without a first name or last name which presently is possible. To mitigate this, we just need to modify our Student class like so:

让我们看一下上面的学生表。 我们不希望创建一个没有姓氏或姓氏的用户,而现在这是可能的。 为了减轻这种情况,我们只需要像下面这样修改Student类:

With this modification, when you create a Student instance without the first name or last name attributes, it is an invalid student and active records will not persist it to the database.

通过此修改,当您创建一个没有名字或姓氏属性的Student实例时,它是无效的Student,并且活动记录不会将其持久化到数据库中。

Active record also provides us with methods to check if our data is valid or invalid:

活动记录还为我们提供了检查数据是否有效的方法:

With this, we do not even have to attempt to save the data.

这样,我们甚至不必尝试保存数据。

Apart from just preventing the data from being persisted, Active Record also provides an error list that holds the attributes that failed validations and user-friendly messages to present to the users. These errors can be accessed as shown in the snippet below.

除了防止数据持久存储外,Active Record还提供了一个错误列表,其中包含验证失败的属性和向用户呈现的用户友好消息。 如下面的代码片段所示,可以访问这些错误。

There is a lot more on validation but it’s not the topic of this article. For a deep dive, you can get an in-depth explanation from the ruby on rails guide chapter on Validation.

关于验证还有更多内容,但这不是本文的主题。 要深入了解,您可以从“验证”一章中的“ ruby​​ on rails”指南中获得深入的解释。

自定义验证 (Custom Validation)

Sometimes, we might want to use certain validations that are more than just ensuring the presence of an attribute, length, uniqueness, or any of the helpers provided by Active Record. Luckily, Active Record allows us to define our own custom validations, which is the point of this article.

有时,我们可能要使用某些验证,而不仅仅是确保属性,长度,唯一性或Active Record提供的任何帮助程序的存在。 幸运的是,Active Record允许我们定义自己的自定义验证,这就是本文的重点。

So, let’s say for our Student model, we have a compulsory student registration number column. It has to be filled from the registration form (I know this can be auto-generated) which should always start with the registration year. Now, Active Record does not provide this kind of validation out of the box, but has made it possible for us to define it and use it.

因此,对于我们的学生模型,我们有一个必修的学生注册号列。 必须从注册表格(我知道这可以自动生成)中填写,该表格应始终以注册年份开始。 现在,Active Record不再提供这种验证,而是使我们可以定义和使用它。

There are mainly two ways to define your own validation logic:

定义您自己的验证逻辑主要有两种方法:

  • Custom Validator

    自定义验证器
  • Custom Methods

    定制方法
自定义验证器 (Custom Validator)

To validate using a custom validator, you just need to define your validation logic in a class that extends ActiveModel::Validator and implements the validate method, which takes the record to be validated as its argument.

要使用自定义验证器进行验证,您只需要在扩展ActiveModel :: Validator并实现validate方法的类中定义验证逻辑,该方法将要验证的记录作为其参数。

If validation fails, it adds the attribute to the errors array along with its error message. So, in our case, we’ll have RegNumValidator as seen below:

如果验证失败,则会将属性及其错误消息添加到错误数组。 因此,在本例中,我们将看到RegNumValidator,如下所示:

To use this validator in the Student model, we use the validates_with method:

要在学生模型中使用此验证器,我们使用validates_with方法:

With this, when a user tries to create a student with the wrong registration number, the record creation fails and an error message can be shown.

这样,当用户尝试使用错误的注册号创建学生时,记录创建失败,并且可能显示错误消息。

定制方法 (Custom Methods)

To use custom methods for validation, you just need to define a method to use for validation in your model class and call it like you would call any of the in-built validations — using validate. Using the same logic as what we had above, our model would look like this:

要使用自定义方法进行验证,您只需要在模型类中定义一种用于验证的方法,然后像调用任何内置验证一样调用它即可—使用validate 。 使用与上面相同的逻辑,我们的模型将如下所示:

结论 (Conclusion)

I hope this article has given you the necessary knowledge to begin to explore Active Records validation and custom validation especially. Whenever you have a validation rule that is not part of the existing active record validation API, you can write one yourself.

我希望本文为您提供了必要的知识,特别是开始探索Active Records验证和自定义验证。 只要您拥有的验证规则不属于现有活动记录验证API的一部分,就可以自己编写。

Active Record Validations — Ruby on Rails GuidesValidations are used to ensure that only valid data is saved into your database. For example, it may be important to…guides.rubyonrails.org

Active Record验证— Ruby on Rails指南 验证用于确保仅将有效数据保存到数据库中。 例如,可能很重要…… guides.rubyonrails.org

翻译自: https://www.freecodecamp.org/news/a-quick-look-at-rails-custom-validation-9ab7e0f1af81/

rails自定义验证

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值