Ruby on rails 坎坎授权论坛
我正在做一个使用RoR的项目,RoR是一个社交留言板(互联网论坛),在这个项目中,每个用户都可以创建多个留言板,并加入其他用户的多个留言板 我不想重新发明轮子,所以我使用Desive进行身份验证,使用CanCan进行授权。但是,我在实施CanCan时遇到了一些问题,原因如下:Ruby on rails 坎坎授权论坛,ruby-on-rails,ruby,gem,authorization,cancan,Ruby On Rails,Ruby,Gem,Authorization,Cancan,我正在做一个使用RoR的项目,RoR是一个社交留言板(互联网论坛),在这个项目中,每个用户都可以创建多个留言板,并加入其他用户的多个留言板 我不想重新发明轮子,所以我使用Desive进行身份验证,使用CanCan进行授权。但是,我在实施CanCan时遇到了一些问题,原因如下: class Board < ActiveRecord::Base has_many :memberships has_many :users , :through => :memberships end
class Board < ActiveRecord::Base
has_many :memberships
has_many :users , :through => :memberships
end
class User < ActiveRecord::Base
has_many :memberships
has_many :boards, :through => :memberships
end
class Membership < ActiveRecord::Base
ROLE = ['Administrator', 'Moderator','Member', 'Banned']
belongs_to :user
belongs_to :board
end
classboard:会员资格
结束
类用户:会员资格
结束
类成员身份
角色不属于用户本身,它属于用户和董事会之间的关系,即成员关系。所以仅仅知道谁是当前的用户还不够,我还需要知道显示的是哪个板,所以我想我必须将成员身份而不是用户发送给能力类初始值设定项?任何指导都将不胜感激 你走的路是对的 如果你还没有,创建一个全新的能力。e、 g.
可登机性
。我发现在传递额外的依赖项时不要害羞,让CanCan做尽可能多的合理评估是很有用的
class BoardAbility
include CanCan::Ability
attr_reader :requested_by, :requested_resource
def initialize requested_by, requested_resource
return nil unless (requested_by.is_a?(User) && requested_resource.is_a?(Board))
@requested_by = requested_by
@requested_resource = requested_resource
default_rules
end
private
def default_rules
# common abilities to all users
can :flag_offensive, :all
can :view_thread_count, :all
# find this user's role to this board to define more abilities
role = Membership.where(user_id: requested_by.id, board_id: requested_resource.id).pluck(:role).first
if ['Administrator', 'Moderator'].include? role
can :ban_users, Board, {id: requested_resource.id}
end
end
end
然后在BoardController中定义一个私有方法,表示我们没有使用默认的CanCan能力类
def current_ability
@current_ability ||= BoardAbility.new(current_user, @board)
end
然后,当您在BoardController中时,使用通常的CanCan DSL
authorize! :ban_user, @board