gpt4 book ai didi

ruby-on-rails - CanCan 和多态关联(Eager Loading 错误)

转载 作者:行者123 更新时间:2023-12-04 18:09:19 25 4
gpt4 key购买 nike

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

我有步骤,每个步骤都有一个可踏步的(讲座、测验或其他一些 Action )。我需要一个有效的 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 )

最佳答案

你应该能够做到这一点:

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

关于ruby-on-rails - CanCan 和多态关联(Eager Loading 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18896842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com