Search code examples
ruby-on-railsruby-on-rails-3validationintrospection

Rails: list accepted values of "validates :inclusion" field


I have a model like this

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

is it posible to list all accepted values for some field ? For example get the list of %w(radio check stars) from the field "kind"


Solution

  • There may be a nicer way to do this, but some playing around in the console got me this:

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