ruby-on-rails - Rails 和 CanCan : If user is logged in then allow him/her to view index page?

标签 ruby-on-rails cancan

我在rails 3应用程序上使用authlogic和cancan,我想允许所有登录的用户访问用户索引页面,我已经尝试过类似的操作,但它似乎不起作用:

能力等级:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    can :index, User if UserSession.find

    can :read, User if UserSession.find

end

Controller :

def index
    @users = User.search(params[:search]).order('username').page(params[:page]).per(1)
    authorize! :index, @users
  end




def show
     @user = User.find(params[:id])
     authorize! :read, @user
     respond_to do |format|
     format.html # show.html.erb
     format.xml  { render :xml => @user }
    end
  end

谢谢

最佳答案

我发现在 Controller 顶部使用 load_and_authorize_resource 更容易。然后你的能力类包含所有的能力逻辑,而不是让它散布在你的 Controller 上。

能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    if user
      can :index, User
      can [:show, :edit, :update, :destroy], User, :id => user.id
    end
  end
end

users_controller.rb

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.search(params[:search]).order('username').page(params[:page]).per(1)
  end

  def show
  end

  ...

end

我已经有一段时间没有使用 authlogic 了,因为我现在倾向于使用 devise,所以我不确定我的示例代码是否已准备好 authlogic。如果您不想使用 load_and_authorize_resource,我的代码显示了如何限制用户在能力类中可以看到的内容,但在您的代码中,我会将 :read 更改为:显示

关于ruby-on-rails - Rails 和 CanCan : If user is logged in then allow him/her to view index page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153637/

相关文章:

ruby-on-rails - CanCan 中最安全和最可靠的方式来执行访客、用户、管理员权限

javascript - 尝试使用 capybara-angular 和 capybara-ng gems 实现自动化 - 帮助和示例。-

ruby-on-rails - ActiveRecord::Migration 的未定义方法 `check_pending!'(Rails 教程)

ruby-on-rails - 使用 Ruby on Rails 模型

ruby-on-rails - 为什么我不能在 Cloud9 上安装 Ruby gem rspec?

ruby-on-rails - cancan + rspec = 未初始化常量 Anonymou(无 s)?

ruby-on-rails - 在两个不同的模型用户和事件管理员的情况下,如何为设计定义自定义失败?

ruby-on-rails - 应用程序逻辑与授权

ruby-on-rails - CanCan 联想能力

ruby-on-rails - CanCan 错误地拒绝管理员访问