【问题标题】:CanCan and polymorphic associations (Eager Loading error)CanCan 和多态关联(Eager Loading 错误)
【发布时间】:2013-09-19 14:03:06
【问题描述】:

我正在尝试根据关联模型上的列(例如can :read, Step, 'steppable' => {published: true})定义用户访问某些内容的能力,问题是它是多态关联,因此它找不到可步进的表,因为它不存在。

我有步骤,每个步骤都有一个可分步(讲座、测验或其他动作)。我需要一个可以工作的 activerecord 查询。我试过了:

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 )

【问题讨论】:

  • 您是否尝试过Step.includes(:steppable).all,只是为了检查一下?你的模型是什么样的?我们需要更多信息...
  • 是的,Step.includes(:steppable).all 有效,但 Step.includes(:steppable).where('steppable' => {published: true}).all 导致相同的@987654329 @ 错误。我用模型信息更新了问题。

标签: ruby-on-rails activerecord cancan


【解决方案1】:

你应该可以这样做:

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 类执行此操作,但它解决了急切加载多态关联问题。稍微干一点:

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

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

【讨论】:

  • 谢谢 Josh,我会试一试。
  • 这个例子太简单了,你可能想在 steppable 记录上定义哈希条件,这取决于模型,它会崩溃,因为 CanCanCan 会尝试调用该模型不存在的属性.
【解决方案2】:

你可以这样做:

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

或者如果您真的想对关联模型不可知论:

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

【讨论】:

  • 这些都不行。我想对关联模型不可知论,为了让它能够使用 CanCan 获取记录,它必须使用数据库列来完成(参见github.com/ryanb/cancan/wiki/defining-abilities
  • 您能否更准确地说明您要使用 CanCan 做什么?
  • 是的,我正在尝试设置类似:can :read, Step, steppable: {published: true} 但这会导致上述错误。我可以用 can :read, Step do |step| 来做step.steppable.published?结束,但这不允许使用 CanCan 的 access_by 方法获取项目。
  • 那我想我帮不了你了; )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
相关资源
最近更新 更多