6

我正在尝试定义用户基于关联模型上的列访问某些内容的能力(例如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 )

4

2 回答 2

9

你应该能够做到这一点:

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在每个类中定义不同。

于 2013-09-19T23:08:48.887 回答
0

你可以这样做:

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

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

Step.all.select { |s| s.steppable.published? }
于 2013-09-19T14:58:03.013 回答