繁体   English   中英

CanCan和多态关联(急切加载错误)

[英]CanCan and polymorphic associations (Eager Loading error)

我正在尝试定义用户基于关联模型上的列访问内容的能力(所以可以像can :read, Step, 'steppable' => {published: true} ),问题是它是一个多态关联因此它找不到steppable表,因为它不存在。

我有步骤,每个步骤都有一个步骤(演讲,测验或其他操作)。 我需要一个有效的记录查询,它将起作用。 我试过了:

Step.includes(:steppable).where('steppable' => {published: true})

Step.joins(:steppable).where('steppable' => {published: true})

但是两者都导致ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :steppable

模型看起来像这样:

class Step < ActiveRecord::Base
   ...
   belongs_to :steppable, polymorphic: true, dependent: :destroy
   ...
end

class Lecture
   ...
   has_one :step, as: :steppable, dependent: :destroy
   ...
end

注意:我想对相关模型不了解 ,为了使其能够使用CanCan来获取记录,必须使用数据库列来完成(请参见github.com/ryanb/cancan/wiki/defining-abilities

您应该可以执行以下操作:

can :read, Step, steppable_type: 'Lecture', steppable_id: Lecture.published.pluck(:id)
can :read, Step, steppable_type: 'OtherThing', steppable_id: OtherThing.published.pluck(:id)

您必须为每个Steppable类都执行此Steppable ,但是它Steppable急于加载多态关联的问题。 要干一点:

[Lecture, OtherThing].each do |klass|
  can :read, Step, steppable_type: klass.to_s, steppable_id: klass.published.pluck(:id)
end

在这种情况下,只要每个steppable类的作用域steppable published ,就可以将任何steppable类添加到该数组中,即使在每个类中published的定义不同。

您可以这样操作:

lectures = Lecture.where(published: true)
steps = Step.where(steppable_type: 'Lecture', steppable_id: lectures)

或者,如果您真的想对关联的模型不了解,请执行以下操作:

Step.all.select { |s| s.steppable.published? }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM