Rails 嵌套包含动态类
如果我有一个类 A,其中有许多 B,但 B 只是一个类的 ID,并且实际上可以采用多个不同类的形式,我可以根据 B 是什么类动态加载 B 的关联吗?
例如,如果 B 是 Car 类的 id,我是否能够以某种方式急切地加载 B.wheels。但如果是 Dog 类型,我可以获得 B.Toys 吗?这一切都将通过 A 进行,而 A 只属于一种类型。我尝试使用语法:
notifs = current_user.notifications.includes(target: [:wager_members, :disputes, :games])
其中通知属于 A 类,:target 将是动态 B 类,而 :wager_members、:disputes 和 :games 将是取决于 B 类的关联。
但是,我收到一条错误消息,指出 B 类没有 F 类,这是有道理的,因为 B 类会动态更改。有没有一种方法/语法可以一次性加载所有嵌套关联?
我想知道是否需要重新考虑模型关联以使其可行。
If I have a class A that has many B, but B is just the ID of a class, and can actually take the form of multiple different classes, can I eager load the associations of B dynamically based off what class it is?
For example, if B was the id of class Car, am I somehow able to eager load B.wheels. But also if it's of type Dog, can I get B.Toys? This would all be through A, which of only one class type. I tried with syntax:
notifs = current_user.notifications.includes(target: [:wager_members, :disputes, :games])
Where notifications would be of class A, :target would be the dynamic class B, and :wager_members, :disputes, and :games would be the associations depending on what class B is.
However, I get an error saying there is no class F for class B, which makes sense because class B dynamically changes. Is there a way/syntax to load all nested associations in one fell swoop?
I'm wondering if I need to rethink model associations to make it feasible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
多态关联是这里的关键:
https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
下面是您的关联在类级别上的大致样子
您应该能够执行以下操作:
实际上,您可以跳过目标模型并将多态关联移至通知本身。不过,如果您需要添加一些自定义逻辑,这可能很有用。结果是这样的:
Polymorphic associations are key here:
https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
Here is roughly what your associations should look like at the class level
You should then be able to do something like this:
Really you can skip the target model and move the polymorphic association to the notification itself. Though may be useful if you need to add some custom logic. This results in this: