gpt4 book ai didi

ruby - Devise & CanCan——CanCan 2.0 API 的问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:27 26 4
gpt4 key购买 nike

我想为我的 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

最佳答案

我觉得代码不错。如果您尝试先简化第二个条件并取出客户条件怎么办?也许去掉“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

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

关于ruby - Devise & CanCan——CanCan 2.0 API 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8442668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com