我有一个简单的应用程序与设计的身份验证系统.我尝试将角色添加到用户模型中.但没有任何反应.
我做的是
创建了角色模型并将其链接到用户模型:
$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
就这样.我还想知道如何让用户在注册时选择任何这些角色
解决方法
首先,您可以在用户类中使用枚举,而不是使用关联:
class User < ActiveRecord:Base enum role: {seller: 0,buyer: 1,admin: 2} ... end
您需要迁移才能将角色(整数)列添加到用户的表中.
在您的终端:
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 %>
协会here还有更多的例子.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。