【问题标题】:Adding a validation error with a before_save callback or custom validator?使用 before_save 回调或自定义验证器添加验证错误?
【发布时间】:2013-10-23 14:32:49
【问题描述】:

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

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

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

假设我只想让高级用户能够添加 tigerslionsrhinos。我该怎么办?最好是用before_save 方法吗?

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

提前致谢!

【问题讨论】:

  • 不,它不会工作。我想您应该改用自定义验证器。

标签: ruby-on-rails ruby ruby-on-rails-3 validation


【解决方案1】:
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

【讨论】:

  • “和”?你的意思是“&amp;&amp;”?
  • 啊哈!惊人的。感谢您的帮助!
【解决方案2】:

如果您想在 before_save 中添加验证错误,您可以引发异常,然后在控制器中添加错误,如下所示:

class Listing < ActiveRecord::Base    
  before_save :premium_category

  private

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

然后在您的控制器中执行以下操作:

begin 
    @listing.update(listing_params)
    respond_with(@listing)
rescue Exceptions::NotPremiumUser => e
      @listing.errors.add(:base, e.message)
      respond_with(@listing)    
end

然后在 /lib 文件夹中添加这样的类:

module Exceptions
  class NotPremiumUser < StandardError; end
end

但在您的情况下,我认为使用 validate 方法是更好的解决方案。

干杯,

【讨论】:

    【解决方案3】:

    你可以使用validates_exclusion_of:

    validates :category, :exclusion => {
      :in => ['list', 'of', 'invalid'],
      :message => 'must not be premium category',
      :unless => :user_is_premium?
    }
    
    protected
    
    def user_is_premium?
      self.user.premium?
    end
    

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 2012-05-07
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多