使用 CanCanCan

问题描述

我在多对多关系中有 3 个模型:

class User < ApplicationRecord
  has_many :participations
  has_many :attended_events,through: :participations,source: :event
end
class Event < ApplicationRecord
  has_many :participations
  has_many :participants,source: :user
end
class Participation < ApplicationRecord
  belongs_to :user
  belongs_to :event
end

我想授权用户创建新的参与,前提是他还不是活动的一部分。 换句话说,只有当用户还没有与同一事件相关联的参与时,他才能创建参与。

这是我已经尝试过的,但即使用户还不是活动的参与者,访问也总是被拒绝:

cannot [:new,:create],Participation,id: user.participation_ids

cannot [:new,event_id: user.attended_event_ids

cannot [:new,event: { id: user.attended_event_ids }

我确保已在 Participation#new 操作中加载了正确的 @event

我假设我的 event 语句中的 event_id / cannot 指的是它。这是一个正确的假设吗?

编辑:

我意识到我忘记定义未达到条件时实际授权 new 操作的能力

can :new,Participation
cannot :new,event_id: user.attended_event_ids

# This cannot statement works too
# cannot :new,event: { id: user.attended_event_ids }

但现在用户总是可以创建新的参与(好像没有 cannot 语句一样)。

我设法让它像这样工作:

在参与控制器中:

class ParticipationsController < ApplicationController

 # load_and_authorize_resource only: [:new]  removed this line

  def new
    @participation = Participation.new(event: @event) # added this line
    authorize! :new,@participation  # added this line
  end
end

所以我是手动完成的,这并不理想。我认为 event_id 不会自动引用我在 Participation#new 操作中加载的 @event...

如何使用 load_and_authorize_resource 方法而不是手动执行此操作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...