如何在rails应用程序中为我的用户添加角色? [英] how to add roles to my users in rails app?
问题描述
我有一个简单的应用程序,带有来自 devise 的身份验证系统.我尝试向用户模型添加角色.但什么也没发生.
I have a simple app with an authentication system from devise. I tried adding roles to the user model. But nothing happens.
我所做的是创建角色模型并将其链接到用户模型:
$ rails g model Role name:string
$ rails g migration addRoleIdToUser role:references
$ rake db:migrate
(按照设计维基的指示)
(as directed by the devise wiki)
然后在我的模型中:
class User < ActiveRecord::Base
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :users
end
用我的角色设置seeds.rb:
['seller', 'buyer', 'admin'].each do |role|
Role.find_or_create_by({name: role})
end
然后
$ rake db:seed
仅此而已.我也想知道如何让用户在注册时选择这些角色中的任何一个
That's all. And I also want to know how to make the user chose any of these roles at the time of signup
推荐答案
首先,您可以在用户类中使用 enum
而不是使用关联:
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
您需要迁移以将 role
(整数)列添加到您的用户表中.
You'll need a migration to add a role
(integer) column into your user's table.
在您的终端中:
rails g migration add_role_to_users
然后编辑迁移文件:
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :integer
end
end
然后你可以例如使用 SimpleForm
gem 让用户在注册时选择他/她的角色:
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 %>
但 SimpleForm 也有很好的关联:
But SimpleForm is also good with associations:
<%= f.association :role, as: :radio_buttons %>
这篇关于如何在rails应用程序中为我的用户添加角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!