多态 Rails 关联(倒退?)
我的 Rails 应用程序中有一个多对一的多态 Rails 关联,用于“案例”模型。 有很多东西都有案例,所以我通过执行“thing_that_has_a_case.case”来访问每个东西都有的案例。
然而,我正在尝试走另一条路,但我不知道如何走。 我可以访问案例对象,但我想访问正在案例中的东西。 Rails 有办法做到这一点吗? 我可以用一个丑陋的开关来做到这一点,它为每种类型的对象执行不同的 sql 查找,但我希望 Rails 能有更好的方法。 谢谢!
I have a many to one polymorphic rails association in my rails app for a 'case' model. There are many things that have cases, so I access the case each thing has by doing 'thing_that_has_a_case.case'.
However, I'm trying to go the other way and I'm not sure how. I have access to the case object but I want to access the thing that is being cased. Does rails have a way to do this? I could do it with an ugly switch that does a different sql find for each type of object, but I was hoping rails would have a better way. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将类似的内容添加到您的案例模型中:
..假设您的案例模型中有字段
parent_id
和parent_type
(将第一个参数更改为belongs_to
取决于您如何命名这些关联字段)。 一旦有了这个,您应该就能够引用给定案例实例的case.parent
。而且,为了澄清一下,这种关系的一方面是这样的:(
我假设你已经根据你的描述进行了这项工作)
You can add something like this to your case model:
..which assumes you have fields
parent_id
andparent_type
in your case model (change the first argument to thebelongs_to
depending on how you have named these association fields). Once you have this, you should just be able to refer tocase.parent
for a given case instance.And, just to clarify, the one side of this relationship has something like:
(I'm assuming you already have that working based on your description)