mat*_*fel 5 activerecord ruby-on-rails cancan
我正在尝试定义用户基于关联模型上的列访问内容的能力(类似can :read, Step, 'steppable' => {published: true}),问题是它是一个多态关联,因此无法找到可步进表,因为它不存在。
我有步骤,每个步骤都有一个步骤(演讲,测验或其他操作)。我需要一个有效的记录查询,它将起作用。我试过了:
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
Run Code Online (Sandbox Code Playgroud)
和
class Lecture
...
has_one :step, as: :steppable, dependent: :destroy
...
end
Run Code Online (Sandbox Code Playgroud)
注意:我想对相关模型不了解,为了使其能够使用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)
Run Code Online (Sandbox Code Playgroud)
您必须为每个Steppable类都这样做,但是它避免了急于加载多态关联的问题。要干一点:
[Lecture, OtherThing].each do |klass|
can :read, Step, steppable_type: klass.to_s, steppable_id: klass.published.pluck(:id)
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下,只要每个steppable类都有一个scope published,就可以将任何steppable类添加到该数组中,即使published每个类中的定义不同。
| 归档时间: |
|
| 查看次数: |
1144 次 |
| 最近记录: |