Ruby On Rails Rolify + CanCanCan + Devise 允许用户仅编辑他们的帖子



我已经使用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 %>

我同意理查德·派克的回答。但是,我只想指出,不需要为来宾用户(未登录)提供服务。初始值设定项在新对象(即对象的构造函数)的实例化时调用。

因此,上述能力类可以如下所示:

#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

最新更新