我正在尝试用Rails 4创建一个应用程序。我使用bootstrap,设计简单的形式和role_model宝石。
profile.rb
class Profile < ActiveRecord::Base
include RoleModel
#reminder for roles (RoleModel): always add new roles to the end of this line - don't change the order
roles :admin, :manager,
:student, :educator, :researcher, :ktp, :faculty_manager, :ip_asset_manager,
:sponsor,
:project_manager, :representative, # for both uni and industry
:grantor, :investor, :adviser, :innovation_consultant, :panel_member,
:participant, :guest, :pending
# Other stuff goes here
end
然后在我的个人资料视图中,我有一个表格,我会问用户他们来自哪里。我想根据用户的角色以不同的方式表达问题,我想根据该角色使用不同的选项数组。例如,如果当前用户是学生,那么阵列应该填充一系列大学。
<div class="col-md-3 col-md-offset-1">
<% if current_user.profile.has_any_role?(:student, :educator, :researcher, :ktp, :faculty_manager, :ip_asset_manager) %>
<%= f.label 'Select your university', :class => 'question-project' %>
<% elsif current_user.profile.has_role?(:sponsor) %>
<%= f.label 'Select your organisation', :class => 'question-project' %>
<% elsif current_user.profile.has_any_role?(:grantor, :investor, :adviser, :innovation_consultant, :panel_member) %>
<% end %>
</div>
<div class="col-md-7">
<div class="response-project">
<% if current_user.profile.has_any_role?(:student, :educator, :researcher, :ktp, :faculty_manager, :ip_asset_manager) %>
<%= f.collection_select :university_id, University.all, :id, :name, prompt: 'Select your university' %>
<% elsif current_user.profile.has_role?(:sponsor) %>
<%= f.collection_select :organisation_id, Organisation.all, :id, :name, prompt: 'Select your organisation' %>
<% elsif current_user.profile.has_any_role?(:grantor, :investor, :adviser, :innovation_consultant, :panel_member) %>
<%= f.collection_select :firm_id, Firm.all, :id, :name, prompt: 'Select your organisation' %>
<% else %>
<%= current_user.profile.id %>
<% end %>
我有最后的声明来证明以上所有内容都不起作用。当我尝试这个时,使用角色为:student的用户应该让我沿着第一条路线前进。它不起作用。我得到了user.profile.id。
有谁能看到我做错了什么?
答案 0 :(得分:1)
您忘记在模型类
之上添加require 'role_model'
<强>更新强>
require 'rubygems'
require 'role_model'
class Profile < ActiveRecord::Base
attr_accessor :roles_mask
include RoleModel
#reminder for roles (RoleModel): always add new roles to the end of this line - don't change the order
roles_attribute :roles_mask
roles :admin, :manager,
:student, :educator, :researcher, :ktp, :faculty_manager, :ip_asset_manager,
:sponsor,
:project_manager, :representative, # for both uni and industry
:grantor, :investor, :adviser, :innovation_consultant, :panel_member,
:participant, :guest, :pending
# Other stuff goes here
end
在您的情况下,u.roles
为空:
> u.roles
=> #<RoleModel::Roles: {}>
从控制台您需要分配角色:
u = User.first
> u.roles
=> #<RoleModel::Roles: {}>
> u.roles= [:admin]
=> [:admin]
> u.roles
=> #<RoleModel::Roles: {:admin}>
> u.roles << :manager
=> #<RoleModel::Roles: {:admin, :manager}>
> u.roles
=> #<RoleModel::Roles: {:admin, :manager}>
> u.has_any_role? :author, :manager
=> true
进一步Reference