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

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 %>

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

因此,上述能力class可以如下:

#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