How to create a dropdown list of valid values ​​set by validates_inclusion_of?

I have a model object Userwhose attribute is permissionlimited to validates_inclusion_of- ['user','org_admin','site_admin']. When developing the create / edit form for this object, I do not want to duplicate this list if it changes later. Is there a “Rails” way to do this, or do I just need to extract a list of valid values ​​into an attribute that is accessible from outside the instance?

+5
source share
1 answer

If I really wanted to work with strings, I would probably define a User :: PERMISSIONS constant that includes the specified permissions.

class User < ActiveRecord::Base
  PERMISSIONS = ['user','org_admin','site_admin']
  validates_inclusion_of :permission, :in => PERMISSIONS
end

( simple_form )

simple_form_for(@user) do |f|
  f.input :permission, :as => :select, :collection => User::PERMISSIONS
end

allow_id .

, , .

+4

All Articles