[英]how to add roles to my users in rails app?
我有一個簡單的應用程序與設計的身份驗證系統。 我嘗試將角色添加到用戶模型中。 但沒有任何反應。
我做了什么創建了角色模型並將其鏈接到用戶模型:
$ rails g model Role name:string
$ rails g migration addRoleIdToUser role:references
$ rake db:migrate
(按照設計維基的指示)
然后在我的模型中:
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
就這樣。 我還想知道如何讓用戶在注冊時選擇任何這些角色
首先,您可以在用戶類中使用enum
,而不是使用關聯:
class User < ActiveRecord:Base
enum role: {seller: 0, buyer: 1, admin: 2}
...
end
您需要遷移才能將role
(整數)列添加到用戶的表中。
在您的終端:
rails g migration add_role_to_users
然后編輯遷移文件:
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :integer
end
end
然后你可以使用SimpleForm
gem讓用戶在注冊時選擇他/她的角色:
<%= simple_for for @user do |f| %>
...
<%= f.select :role, collection: User.roles.keys.to_a %>
...
<% end %>
但SimpleForm對關聯也很好:
<%= f.association :role, as: :radio_buttons %>
有消協更多的例子在這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.