Select enum from form to set role

前端 未结 5 1451
醉酒成梦
醉酒成梦 2021-02-01 22:38

Ruby on Rails 4.1

I am using Devise with enum role. It currently sets a defualt role when the User is created. I want to add a field to the form that creates Users to se

5条回答
  •  情书的邮戳
    2021-02-01 23:24

    To start, enum is not the name of an attribute. The name of the attribute is role.

    Take a look at the rails-devise-pundit example application, specifically the file app/views/users/_user.html.erb which is a partial that creates a form to allow the administrator to change a user's role. I doubt you want to use a collection_select for helper (that is suitable if you have a separate Role model). Instead, an ordinary select form helper will work.

    Here's a simple example that hardcodes the role options:

    <%= f.select(:role, [['User', 'user'], ['Vip', 'vip'], ['Admin', 'admin']]) %>
    

    Here is a better example that avoids hardcoding the roles in the form:

    <%= f.select(:role, User.roles.keys.map {|role| [role.titleize,role]}) %>
    

    The statement obtains an array of roles from the User model and constructs an array of key-value pairs using the map method.

提交回复
热议问题