[英]Rails cancan ability.rb
並開始學習康康+設計
我有“用戶”表(設計)
我有“職位”表(帶有“ user_id”字段)
我有“角色”表(帶有“名稱”字段)
我有users_roles(帶有'user_id'和'role_id')
我以“用戶”角色創建了2個用戶
並創建1個具有“ admin”角色的用戶
user.rb
has_many :posts
has_many :users_roles
has_many :roles, :through => :users_roles
role.rb
has_many :users_roles
has_many :users, :through => :users_roles
users_role.rb
belongs_to :user
belongs_to :role
還有一個問題:
i create ability.rb
同
def initialize(user)
user ||= User.new
if user.persisted?
#loged in
can :read, Post
can :create, Post
can :update, Post , :user_id => user.id
can :destroy, Post , :user_id => user.id
else
#not logged
can :read, Post
end
在我的views / posts / index.html.erb中
<% @posts.each do |post| %>
<tr>
<td><%= post.user.email %></td>
<td><%= post.title %></td>
<td><%= post.text %></td>
<td><%= link_to 'Show', post %></td>
<% if can? :update, Post %>
<% if current_user.id == post.user.id %>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<% end %>
<% end %>
<% if can? :destroy, Post %>
<% if current_user.id == post.user.id %>
<td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
<% end %>
</tr>
<% end %>
</table>
<br />
<!-- ???почему Post ? -->
<% if can? :create, Post %>
<%= link_to 'New Post', new_post_path %>
<% end %>
在這種情況下,我檢查是否用戶登錄-他可以讀取和創建,更新,銷毀(如果他是autor),如果用戶未登錄(來賓)-只能讀取
但我不知道如何更改我的能力。
注意我已經有角色表(具有2個角色)和3個用戶(1個具有admin角色,2個具有user角色)
這就是我在應用程序中實現cancan來管理角色和來賓用戶的方式。
只需使用if user.role == role
來驗證用戶是否具有正確的角色。
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role == "author"
#
can :read, Post
can :create, Post
can :update, Post , :user_id => user.id
can :destroy, Post , :user_id => user.id
# a simple way to realize read create update and destroy is :manage
# can :manage, Post, :user_id => user.id
else
if user.role == "admin"
# User with role admin can manage all on all models
can :manage, :all
else
# Guest user can only read something
can :read, Post
# or
# can :read, [SomeModel1, Somemodel2]
# can :read, :all # this means he can read all models
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.