看了这个能力.rb。我允许管理员管理 一切(那部分有效),但我如何让用户只是查看 并使用cancan编辑自己的Logg?目前用户不能 查看任何内容,甚至不是自己创建的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
端
我没有用户控制器。我有loggs控制器:
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
答案 0 :(得分:0)
您需要添加可以读取其Logg的内容,就像您创建或更新一样:
can :read, Logg, :user_id => 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 => user.id
而不是那三个陈述。