Select enum from form to set role

前端 未结 5 1363
醉酒成梦
醉酒成梦 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:06

    Here is how I did it, with internationalization and ordering, and auto select the current_user role if already defined. It assumes that you have a locale file with a roles: category containing all your enum roles such as :

    # your locale file
    en:
     roles:
      admin: "Administrator"
      mode: "Moderator"
    
    
    # model user.rb
    enum role: { admin: 0, mode: 1 }
    ROLES = User.roles.map { |r,| [I18n.t("roles.#{r}"), r] }.sort_by { |r| I18n.t("roles.#{r}") }
    
    # view
    
    <%= f.select :role, User::ROLES, { prompt: t("users.roles.prompt"), selected: @user.role }, { class: "form-control" } %>
    

提交回复
热议问题