开发者

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

开发者 https://www.devze.com 2023-03-20 06:58 出处:网络
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 o开发者_运维问答bj

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 o开发者_运维问答bject, 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消