Rails 嵌套包含动态 class

Rails nested includes with dynamic class

如果我有一个class A,里面有很多B,但是B只是一个class的ID,实际上可以取多个不同的class形式,我可以根据 class 它是什么动态加载 B 的关联吗?

例如,如果 B 是 class 汽车的 ID,我是否能够以某种方式预先加载 B.wheels。但如果它是 Dog 类型,我可以得到 B.Toys 吗?这将全部通过 A,只有一种 class 类型。我尝试使用语法:

notifs = current_user.notifications.includes(target: [:wager_members, :disputes, :games])

其中通知是 class A,:target 是动态 class B,而 :wager_members、:disputes 和 :games 是关联,具体取决于class B 是什么。

但是,我收到一条错误消息,指出 class B 没有 class F,这是有道理的,因为 class B 会动态变化。有没有way/syntax一举加载所有嵌套关联?

我想知道是否需要重新考虑模型关联以使其可行。

多态关联是这里的关键: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

以下是您的联想在 class 级别的大致情况

User
has_many :notifications

Notification
belongs_to :user
belongs_to :target

Target
belongs_to :notify, polymorphic: true # Can be any model

然后您应该能够执行如下操作:

Notification.create(user: user, target: wager_member)
Notification.create(user: user, target: dispute)
Notification.create(user: user, target: game)

notifs = current_user.notifications.includes(target: [:wager_members, :disputes, :games])

notifs.first.target.notify.class.name # "WagerMember"

你真的可以跳过目标模型并将多态关联移动到通知本身。如果您需要添加一些自定义逻辑,虽然可能会有用。结果是:

Notification
belongs_to :user
belongs_to :target, polymorphic: true

notifs.first.target.class.name # "WagerMember"