【问题标题】:Devise & CanCan — Issues with CanCan 2.0 APIDevise & CanCan — CanCan 2.0 API 的问题
【发布时间】:2011-12-09 08:04:28
【问题描述】:

我想为我的 User 模型添加额外的属性,但不想创建单独的 Profile 模型。 我正在尝试使用 RESTful 操作集中的标准 «update» 更新自定义字段:

class UsersController < ApplicationController
  before_filter :authenticate_user!
  # ...
  def update
    @user = User.find(params[:id])
    authorize! :update, @user
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

除了 current_user 能够更新任何用户的个人资料之外,一切都很好。看来我无法限制任何用户操作。我试过了:

can :update, User, :id => user.id

cannot :update, User # at all

没有运气。使用 Devise 1.5.0 和 CanCan 2.0.0.alpha

这是我的能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new(:role => nil) # guest user (not logged in)
    can :access, :all
    if user.admin?
      can :manage, :all
    else
      can :read, Review
      if user.customer?
        can :update, User, :id => user.id
        can [:create, :update, :destroy], Review, :user_id => user.id
      end
    end
  end
end

【问题讨论】:

    标签: ruby ruby-on-rails-3 authentication devise cancan


    【解决方案1】:

    代码对我来说看起来不错。 如果您尝试先简化第二个条件并取出客户条件怎么办?并且也许取出“can :access, :all

    类似:

    class Ability
      include CanCan::Ability
    
      def initialize(user)
        user ||= User.new(:role => nil) # guest user (not logged in)
        if user.admin?
          can :access, :all
        else
          can :read, :all
          can :update, :users, :id => user.id
          can [:create, :update, :destroy], :reviews, :user_id => user.id
        end
      end
    end
    

    您的限制是否适用于评论(该用户只能编辑自己的评论)? 我有一个类似的能力文件,但我总是使用单独的配置文件模型..

    【讨论】:

    • 是的,对于除User CanCan 之外的任何其他型号,它都像一个魅力。我有两个以上的用户角色和更多的资源(我发布了截断的能力.rb)。
    • 糟糕,我撒谎了。好的,所以 CanCan 2.0 使用符号来定义资源而不是常量,这似乎很重要。所以我搞砸了我的能力。rb 非常好。事实证明,我的资源特定限制都不起作用。因此它必须是can :update, :users, :id =&gt; user.id 等等。
    • 原来can :access, :all 也很重要(我需要更好地理解:access:manage 之间的区别)。所以你可以用我的符号来更新你的答案,我会接受的。
    • 啊好吧,很有趣。我仍在使用带有类名的 cancan 1.6.7。将更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多