Rails:列出“validates:inclusion”字段的已接受值

时间:2012-11-02 06:58:42

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

我有这样的模型

class Question < ActiveRecord::Base
  attr_accessible :kind, :question, :state
  belongs_to :section
  validates :question, :kind, :state, :presence => true
  validates :question, :uniqueness => {:scope => [:section_id]}
  validates :kind, :inclusion => {:in => %w(radio check stars)}
  validates :state, :inclusion => {:in => %w(new active answered canceled)}
end

是否可以列出某些字段的所有可接受值?例如,从“kind”字段中获取%w(无线电检查星)的列表

2 个答案:

答案 0 :(得分:2)

可能有一种更好的方法可以做到这一点,但有些人在控制台中玩弄了我:

Question.validators_on(:kind).select{|v| v.kind_of? ActiveModel::Validations::InclusionValidator}.first.options
# => {:in=>["radio", "check", "stars"]}`

答案 1 :(得分:1)

更简洁一点

VALID_KINDS = %w(radio check stars) validates_inclusion_of :kind, in: VALID_KINDS

documentation