ActiveRecord 关系: A has_many Bs AND A has_one B 可以同时存在吗?
我遇到了一种情况,我不确定如何在 Rails 中处理:
事件 has_many :photos
和 照片 belongs_to :event
足够简单
,但是,Event 还需要引用单个“关键”照片。
考虑添加:
事件 has_one :key_photo, :foreign_key => “photo_id”
但是上面给出的 has_many
可以工作吗?如果是这样,如何处理已表示 Photo own_to :event
的照片模型中的反函数?
我可以向照片添加一个布尔列,该列仅适用于一行(“关键”照片),但这似乎是一种浪费......如果只是 1 位列。
I have a situation that I'm not sure how to handle in Rails:
Event has_many :photos
and
Photo belongs_to :event
simple enough
But, Event also needs to reference a single "key" photo.
Thought about adding:
Event has_one :key_photo, :foreign_key => "photo_id"
But will this work given has_many
above? If so, how to handle the inverse in Photo model which already says Photo belongs_to :event
?
I could add a boolean column to Photo that is true for only one row (the 'key' photo) but that seems like a waste...if only of a 1 bit column.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为最简洁的实现是在 :key_photo 事件中添加一个额外的 FK。
I think the cleanest implementation is having an extra FK in events for :key_photo.
对于它的价值,我会添加/使用一位列。它使您的代码更具表现力并更好地展示代码的意图。依赖像“哦,它 has_one AND has_many”这样的怪癖将来会让其他开发人员(比如你自己)感到困惑。
您首先是为其他开发人员编写的,而不是编译器或数据库。事后回来,通过分析使其变得更加美丽/优雅。。从最好的情况来看,这一点导致记录存储问题的可能性微乎其微。
For what it's worth, I would add/use the one bit column. It makes your code more expressive and shows the intent of your code better. Relying on quirks like "oh, it has_one AND has_many" is going to confuse other developers, such as yourself, in the future.
You're writing for other developers first, not the compiler or the database. Come back after the fact and make it more beautiful/elegant, with profiling. The odds that this one bit are going to cause record storage problems are minimal, at best.