![](/img/trans.png)
[英]rails + devise + cancancan + rolify - Unable to view user info in a User index view
[英]Ruby On Rails Rolify + CanCanCan + Devise allow user to edit only their posts
我已經使用Devise + CanCanCan + rolify Tutorial構建了Ruby On Rails
應用程序。
這是我的Ability
模型:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
else
can :read, :all
end
end
end
我想允許用戶編輯自己的帖子,並由他人閱讀帖子。
我該如何實現?
您只需要將user_id
傳遞給hash conditions
:
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
else
can :manage, Post, user_id: user.id #-> CRUD own posts only
can :read, :all #-> read everything
end
end
end
這將允許您使用:
#app/views/posts/index.html.erb
<%= render @posts %>
#app/views/posts/_post.html.erb
<% if can? :read, post %>
<%= post.body %>
<%= link_to "Edit", edit_post_path(post), if can? :edit, post %>
<% end %>
我同意理查德·佩克的回答。 但是,我只想指出,不需要為來賓用戶(未登錄)提供服務。 在實例化新對象(即對象的構造函數)時調用初始化程序。
因此,上面的Ability類可能如下:
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
if user.has_role? :admin
can :manage, :all
else
can :manage, Post, user_id: user.id #-> CRUD own posts only
can :read, :all #-> read everything
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.