how to add roles to my users in rails app?

后端 未结 2 1417
孤城傲影
孤城傲影 2021-02-03 12:53

I have a simple app with an authentication system from devise. I tried adding roles to the user model. But nothing happens.

what i did was created the Role model

2条回答
  •  不要未来只要你来
    2021-02-03 13:34

    First of all, instead of using an association, you can use enum in your user class:

    class User < ActiveRecord:Base
       enum role: {seller: 0, buyer: 1, admin: 2}
    
       ... 
    end
    

    You'll need a migration to add a role (integer) column into your user's table.

    In your terminal:

    rails g migration add_role_to_users
    

    Then edit the migration file:

    class AddRoleToUsers < ActiveRecord::Migration
       def change
          add_column :users, :role, :integer
       end
    end
    

    Then you can e.g. use the SimpleForm gem to let the user choose his/her role during sign up:

    <%=  simple_for for @user do |f| %>
       ...
       <%= f.select :role, collection: User.roles.keys.to_a %>
       ... 
    <% end %> 
    

    But SimpleForm is also good with associations:

    <%= f.association :role, as: :radio_buttons %>
    

    There are more examples for associations here.

提交回复
热议问题