使用 before_save 回调或自定义验证器添加验证错误? [英] Adding a validation error with a before_save callback or custom validator?

查看:41
本文介绍了使用 before_save 回调或自定义验证器添加验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 belongs_to :user 模型 Listing.或者,User has_many :listings.每个列表都有一个分类字段(dogscats 等).User 还有一个名为 is_premium 的布尔字段.

I have a model Listing that belongs_to :user. Alternatively, User has_many :listings. Each listing has a category field that classifies it (dogs, cats, etc). The User also has a boolean field called is_premium.

这是我验证类别的方式...

Here is how I am validating the category...

validates_format_of :category,
                    :with => /(dogs|cats|birds|tigers|lions|rhinos)/,
                    :message => 'is incorrect'

假设我只想让高级用户能够添加老虎狮子犀牛.我该怎么办?最好在 before_save 方法中完成吗?

Let's say I only want to allow premium users to be able to add tigers, lions, and rhinos. How would I go about this? Would it be best to do it in a before_save method?

before_save :premium_check

def premium_check
  # Some type of logic here to see if category is tiger, lion, or rhino.
  # If it is, then check if the user is premium. If it's not, it doesn't matter.
  # If user isn't premium then add an error message.
end

提前致谢!

推荐答案

class Listing < ActiveRecord::Base    
  validate :premium_category

  private

  def premium_category
    if !user.is_premium && %w(tigers lions rhinos).include?(category))
      errors.add(:category, "not valid for non premium users")
    end
  end
end

这篇关于使用 before_save 回调或自定义验证器添加验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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