CanCanCan 无法停止正在编辑的帖子

CanCanCan not stopping posts being edited

我正在做一个 rails 项目,我正在尝试实施 CanCanCan。我安装了 gem 和 运行 命令。然后我将其添加到 ability.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:

      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
      else
        can :update, Post do |post|
          post.user == user
        end
        can :destroy, Post do |post|
          post.user == user
        end
        can :create, Post
        can :read, :all
      end

  end
end

但是,现在在我的项目中,如果我登录到不同的用户,我仍然可以编辑其他用户的帖子。

对于我遗漏的任何帮助,我们将不胜感激。

根据 CanCanCan 文档,

The block is only evaluated when an actual instance object is present. It is not evaluated when checking permissions on the class (such as in the index action). This means any conditions which are not dependent on the object attributes should be moved outside of the block.

don't do this

can :update, Project do |project|
  user.admin? # this won't always get called
end

do this

can :update, Project if user.admin?

所以

can :update, Post do |post|
  post.user == user
end
can :destroy, Post do |post|
  post.user == user
end

所做的更改

can :update, Post if post.user == user
can :destroy, Post if post.user == user

试试 can :manage, Post, :user_id => user.id

如您所见https://github.com/ryanb/cancan/wiki/defining-abilities

通过将 load_and_authorize_resource 添加到我的 posts_controller

解决了错误

我设置它的方式与 nersoh 相同,并且该方法对我有用。您是否尝试过在控制器中授权 Posts 资源?例如,

class PostsController < ActionController::Base
  load_and_authorize_resource
end