如何返回将通过验证的项目列表

问题描述:

我有一个Outlet模型,该模型包含一个允许一些值的包含验证,并且我将展开以获取更多值。如何返回将通过验证的项目列表

我想知道是否有方法可以返回我在包含验证中使用的值的数组吗?

class Outlet < ApplicationRecord 
    belongs_to :user 
    has_many :comments 

    validates :category, :title, :body, :urgency, :user, presence: true 
    validates :title, length: { in: 1..60 } 
    validates :body, length: { in: 1..1000 } 
    validates :urgency, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 } 
    validates :category, inclusion: { in: ['vent', 'rant', 'qualm'] } 
end 

ActiveModel类方法validators_on将返回所有验证对于给定的领域。例如: -

Outlet.validators_on(:category) 
#=> [#<ActiveRecord::Validations::PresenceValidator:0x007fd2350e4b88 ...>, #<ActiveModel::Validations::InclusionValidator:0x007fd23a872cd8 ...>] 

它允许获得包括价值是这样的:

Outlet.validators_on(:category) 
    .find { |validator| validator.is_a?(ActiveModel::Validations::InclusionValidator) } 
    .options[:in] 

它将返回一组选项。

但一个更清洁的方式来达到同样将提取选项类常量:

class Outlet < ApplicationRecord 
    ALLOWED_CATEGORIES = %w(vent rant qualm).freeze 

    # ... 

    validates :category, inclusion: { in: ALLOWED_CATEGORIES } 
end 

然后通过Outlet::ALLOWED_CATEGORIES

+0

伟大的信息访问允许值。谢谢! –