简体   繁体   English

Rails数据建模-has_many的替代方法:给定多态性吗?

[英]Rails data modeling - alternatves to has_many :through, given polymorphism?

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. 如果我在这里“常规”使用多态关联,那么显然user.images将无法正常工作。 Should I just hold my nose, use an :as => :event_images to disambiguate, and define user.all_images if that need ever comes up? 我应该只是hold之以鼻,使用:as => :event_images消除歧义,并在需要时定义user.all_images吗? 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? (当然,要进行验证以确保一致性……但是这似乎在代码上很臭。)是否有第三个解决方案比上述任何一个更漂亮?

I often find it useful to forget the ActiveRecord DSL and work with the data model directly when defining complex relationships. 我经常发现忘记ActiveRecord DSL并在定义复杂关系时直接使用数据模型很有用。 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). 如果一个Image可以同时属于两者,则Image表将需要同时引用user_idevent_id ,这可能需要为空,具体取决于您的用例(用户或事件为可选关系)。 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). 如果Image只能由一个所有者拥有,则可以设置某种多态的所有者关系,将所有者映射到正确的所有者表( owner_idowner_type等)。

Assuming it can belong to both: 假设它可以同时属于两个:

class Image < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class Event < ActiveRecord::Base
  has_many :images
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :events
  has_many :images
  has_many :event_images, :through => :events, :class_name => "Image"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM