6

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

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

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

假设我只想让高级用户能够添加老虎狮子犀牛。我该怎么办?最好用一种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

提前致谢!

4

3 回答 3

10
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
于 2013-10-23T14:38:12.337 回答
5

如果要在 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 方法是一个更好的解决方案。

干杯,

于 2015-04-09T02:53:36.283 回答
2

您可以使用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
于 2013-10-23T14:43:33.417 回答