Rails data modeling - alternatves to has_many :through, given polymorphism? -
I am working on an application that allows users to add images with specific events. The event is owned by a user, the easy solution will definitely be:
class image & lt; ActiveRecord :: Base
related_ to: event
expiration
class event & lt; ActiveRecord :: Base has_many: images
related_to: user
expiration
class user & lt; ActiveRecord :: Base
has_many: events
has_many: images ,: through =>: events
end
Except! There is a problem I also want my users to be able to directly image themselves without the mediator event. If I use the "conventional" multi-union association here, then obviously user.images
will not work properly. Should I just catch my nose, if anybody needs it < To disorganize code>: as =>: event_images , and define user.all_images
? Do I take all the images directly owned by the consumers and alternatively I am connected to the event in any way? (Definitely, a verification to ensure continuity ... but it looks code-smelly.) Is there a third solution that is more beautiful than any of these?
I often forget the ActiveRecord DSL and define complex relationships while working with the data model directly It seems that once the data model is correct you can map it to the model statement.
This is not quite clear from your question that images can be owned by a user or in any event if they can be owned by both at the same time. The issue will determine the data model you use.
If an image can be owned by both, the image table will require a reference to both a user_id and event_id , which can be Is fit based on your usage-case (user or alternate connection occurring) if the image can only be owned by one, then you can establish some kind of polynomial owner qualified relationship You can find the right owner table ( owner_id , owner_type < / Strong> etc etc).
It is of value both:
class image & lt; ActiveRecord :: Base is_to: event is_to: user end class event & lt; ActiveRecord :: Base has has_many: images belong_to: User and class user & lt; ActiveRecord :: Base has has_many: event has_many: images have_many: event_images ,: through = & gt; : Events ,: class_name = & gt; "Image" end
Comments
Post a Comment