郭震 AI公众号:郭震AI

26 模型和数据验证之模型验证和回调

发布日期:

分类: Ruby框架

预计阅读: 3 分钟

阅读次数: 0

预计阅读3 分钟
结构重点7 个
图文要点0 张
正文规模994 字

在上一章中,我们讲解了如何处理表单验证。在这一章中,我们将深入探讨模型的验证和回调。验证是确保数据的完整性和准确性的重要步骤,而回调则允许我们在对象的生命周期中插入自定义逻辑。让我们一起看看如何在 Rails 中实现这些功能。

模型验证

在 Ruby on Rails 中,模型验证用于确保数据在被保存到数据库之前符合特定的规则。我们可以在模型中定义多个验证规则,包括但不限于:必填验证、唯一性验证、格式验证等。

常见的验证类型

  1. 必填验证(validates :attribute, presence: true
    确保字段不为空。

    class User < ApplicationRecord
      validates :name, presence: true
      validates :email, presence: true
    end
    
  2. 唯一性验证(validates :attribute, uniqueness: true
    确保字段的值在数据库中是唯一的。

    class User < ApplicationRecord
      validates :email, uniqueness: true
    end
    
  3. 格式验证(validates :attribute, format: { with: // }
    确保字段值符合特定的正则表达式格式。

    class User < ApplicationRecord
      validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
    end
    
  4. 长度验证(validates :attribute, length: { minimum: , maximum:}
    检查字符串的长度。

    class User < ApplicationRecord
      validates :password, length: { minimum: 6 }
    end
    

自定义验证

你还可以创建自定义验证方法,以实现更复杂的验证逻辑。

class User < ApplicationRecord
  validate :name_cannot_contain_special_characters

  private

  def name_cannot_contain_special_characters
    if name =~ /[^a-zA-Z0-9]/
      errors.add(:name, "cannot contain special characters")
    end
  end
end

模型回调

回调是指在 Active Record 对象的生命周期中的某个时刻自动调用的方法。它们允许我们在特定事件时插入自定义逻辑,比如在创建、更新或删除对象时所执行的操作。

常见的回调类型

  1. before_save
    在保存对象之前执行。

    class User < ApplicationRecord
      before_save :downcase_email
    
      private
    
      def downcase_email
        self.email = email.downcase
      end
    end
    
  2. after_create
    在对象创建后执行。

    class User < ApplicationRecord
      after_create :send_welcome_email
    
      private
    
      def send_welcome_email
        UserMailer.welcome_email(self).deliver_now
      end
    end
    
  3. before_destroy
    在对象删除之前执行。

    class User < ApplicationRecord
      before_destroy :notify_user
    
      private
    
      def notify_user
        # 发送通知给用户
      end
    end
    

回调的使用案例

假设我们有一个博客应用,需要在创建文章时自动设置作者为当前用户,并同时将文章的状态设为“草稿”。我们可以这样实现:

class Post < ApplicationRecord
  belongs_to :user
  before_create :set_default_state

  private

  def set_default_state
    self.state = 'draft'
  end
end

小结

在本章中,我们探讨了模型验证和回调的相关知识,学习了如何使用 Rails 提供的验证方法来确保数据的完整性,同时也了解了如何在模型生命周期的不同阶段插入自定义逻辑。下章中,我们将继续深入模型验证,特别是关联模型的验证策略,让我们一起期待更复杂的模型操作。

接下来,我们将讲解关联模型的验证,这将帮助我们理解如何在多个模型间建立有效的数据关系并进行验证。

希望这章内容能够帮助你更好地理解 Rails 的模型验证和回调机制!

分享文章

转发到常用平台

微信/朋友圈可先复制链接

相关内容

更多相关文章

返回栏目

Reader Messages

读者留言

有问题、补充资料或实测结果,可以直接留下。这里不需要登录。

最多 800 字

为了防刷,每条留言会做长度、链接数量和提交频率限制。

0/800

留言列表

0
正在加载留言...