【问题标题】:cancan authorization for logg not allowing users to see their loggcancan 授权 logg 不允许用户查看他们的日志
【发布时间】:2015-01-06 16:50:15
【问题描述】:

查看ability.rb之后。我已允许管理员管理 一切(那部分工作),但我如何让用户只是,查看 并使用 cancan 编辑自己的 Logg?目前用户无法 根本看不到任何东西,甚至看不到他们自己创建的日志。但是管理员可以 一切。

class Logg < ActiveRecord::Base
has_and_belongs_to_many :user
end

  class User < ActiveRecord::Base
    devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
      ROLES = %w[admin moderator author banned]
   has_and_belongs_to_many :logg

结束

我没有用户控制器。我有日志控制器:

class LoggsController < ApplicationController

 before_action :set_logg, only: [:show, :edit, :update, :destroy]
 load_and_authorize_resource

  respond_to :html

 def index
 @loggs = Logg.all
respond_with(@loggs)
 end

def show
respond_with(@logg)
end

 def new
@logg = Logg.new
respond_with(@logg)
 end

def edit

end

 def create
@logg = Logg.new(logg_params)
@logg.save
respond_with(@logg)
 end

 def update
@logg.update(logg_params)
respond_with(@logg)
end

def destroy
 @logg.destroy
respond_with(@logg)
end

 private
 def set_logg
   @logg = Logg.find(params[:id])
 end

  def logg_params
       params.require(:logg).permit(:name, :date, :time,   
:whats_gone_well_this_week, :whats_not_gone_well_this_week,
 :learnt_anything_new, :what_would_you_like_to_improve, :anything_else)
end
end



class Ability
include CanCan::Ability
def initialize(user)

   if user.nil?
  cannot :read, Logg
  elsif user.admin?
  can :manage, Logg
 else
  can :create, Logg, :user_id => user.id
  can :update, Logg, :user_id => user.id
  end
  end
end

【问题讨论】:

    标签: ruby-on-rails model controller authorization cancan


    【解决方案1】:

    您需要添加可以读取其 Logg 的内容,就像创建或更新一样: can :read, Logg, :user_id =&gt; user.id

    def initialize(user)
    
     if user.nil?
      cannot :read, Logg
     elsif user.admin?
      can :manage, Logg
     else
      can :create, Logg, :user_id => user.id
      can :update, Logg, :user_id => user.id
      can :read, Logg, :user_id => user.id
     end
    end
    

    但鉴于所有这些都是您可能想要的: can :manage, Logg, :user_id =&gt; user.id 而不是那三个语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多