Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dropdown of the valid values set by validates_inclusion_of?

I have a User model object whose permission attribute is restricted by validates_inclusion_of to ['user','org_admin','site_admin']. When designing the create/edit form for this object, I don't want to duplicate this list, in case it changes later. Is there a "Rails way" to do this, or should I just extract the list of valid values into an attribute accessible from outside of the instance?

like image 277
Max Cantor Avatar asked Oct 11 '22 13:10

Max Cantor


1 Answers

If I really wanted to work with strings I would probably define a User::PERMISSIONS constance which includes the mentioned permissions.

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

A simplified form (using simple_form in the example)

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

It would be even neater to create a permissions model and just save the permission_id when you create a new user.

There are probably even better ways to do it so I'm looking forward to other answers.

like image 97
Maran Avatar answered Oct 20 '22 06:10

Maran