设计与开发CanCan — CanCan 2.0 API的问题 [英] Devise & CanCan — Issues with CanCan 2.0 API

查看:102
本文介绍了设计与开发CanCan — CanCan 2.0 API的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为用户模型添加其他属性,并且不想创建单独的Profile模型. 我正在尝试从RESTful操作集中使用标准«update»更新自定义字段:

I'd like to have additional attributes for my User model and don't want to create a separate Profile model. I'm trying to update custom fields with standart «update» from RESTful set of actions:

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能够更新任何用户的配置文件.看来我不能限制任何用户操作.我尝试过:

And it all goes fine except the fact that the current_user is able to update any user's profile. It seems I can't restrict any User action. I've tried:

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

cannot :update, User # at all

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

with no luck. Using Devise 1.5.0 and 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

推荐答案

代码对我来说不错. 如果您尝试先简化第二个条件并取出客户条件,该怎么办?也许拿出可以:access,:all

Code looks good to me. What if you try to simplify the second condition first and take out the customer condition? And maybe take out "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

您对评论的限制是否起作用(该用户只能编辑自己的评论)? 我有一个类似的功能文件,但我始终使用单独的配置文件模型.

Does your restriction work for Reviews (that user can only edit his own reviews) ? I have a similar ability file but I always work with a seperate profile model..

这篇关于设计与开发CanCan — CanCan 2.0 API的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆