Rails 数据建模 - has_many 的替代方案:通过,给定多态性?
我正在开发一个应用程序,允许用户将图像与特定事件关联起来。事件由用户拥有。最简单的解决方案当然是:
class Image < ActiveRecord::Base
belongs_to :event
end
class Event < ActiveRecord::Base
has_many :images
belongs_to :user
end
class User < ActiveRecord::Base
has_many :events
has_many :images, :through => :events
end
除了!有一个问题。我还希望我的用户能够直接拥有图像,而无需中间事件。如果我在这里“按照惯例”使用多态关联,那么显然 user.images
将无法正常工作。如果我只是捂住鼻子,请使用 :as =>; :event_images
来消除歧义,并在需要时定义 user.all_images
?我是否应该将所有图像直接归用户所有并可选择以某种方式与事件关联? (当然,需要进行验证以确保一致性......但这看起来代码很臭。)是否有第三种解决方案比这两种解决方案都更漂亮?
I'm working on an application that allows users to associate images with specific events. Events are owned by a user. The easy solution would of course be:
class Image < ActiveRecord::Base
belongs_to :event
end
class Event < ActiveRecord::Base
has_many :images
belongs_to :user
end
class User < ActiveRecord::Base
has_many :events
has_many :images, :through => :events
end
Except! There is one problem. I also want my users to be able to own images directly, without an intermediary event. If I use polymorphic association "conventionally" here, then obviously user.images
won't work properly. Should I just hold my nose, use an :as => :event_images
to disambiguate, and define user.all_images
if that need ever comes up? Should I have all images owned directly by users and optionally associated with events somehow? (With, of course, a validation to ensure consistency... but that seems code-smelly.) Is there a third solution that is prettier than either of these?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我经常发现在定义复杂关系时忘记 ActiveRecord DSL 并直接使用数据模型很有用。一旦数据模型正确,您就可以将其映射到模型语句中。
从您的问题中尚不清楚图像是否可以由用户或事件拥有,或者它们是否可以同时由两者拥有。这个问题将决定您使用的数据模型。
如果图像可以由两者拥有,则图像表将需要对 user_id 和 event_id 的引用,根据您的用例,该引用可能需要为空(用户或事件是可选关系)。如果图像只能由一个人拥有,您可以设置某种多态可拥有关系,将所有者映射到正确的所有者表(owner_id、owner_type< /strong> 等等)。
假设它可以属于两者:
I often find it useful to forget the ActiveRecord DSL and work with the data model directly when defining complex relationships. Once the data model is correct you can then map it into model statements.
It is not quite clear from your question if Images can be owned by a User or an Event, of if they can be owned by both at the same time. That issue will determine the data model you use.
If an Image can be owned by both, the Image table will need a reference to both a user_id and an event_id, which may need to be nullable depending on your use-case (user or event being optional relationships). If the Image can only be owned by one, you could set up some sort of polymorphic ownerable relationship that maps owners to the right owner table (owner_id, owner_type etc etc).
Assuming it can belong to both: