D
D
Denis Savitsky2012-11-16 10:48:07
Ruby on Rails
Denis Savitsky, 2012-11-16 10:48:07

How to add attachments of different data types (Audio, Video, Documents)?

How to add many attachments of different data types (Audio, Video, Documents)?
Let's say there is an Article.
I want to attach 3 videos, 5 audios, 2 pdfs and 1 picture to the Article. I want to use these attachments in other articles separately from each other.
How can this be embedded using the carrierwave gem , for example?
There is a working code, but it doesn't quite work as it should:

class Post < ActiveRecord::Base<br>
  belongs_to :user<br>
  has_many :attachments<br>
end<br><br>
class Attachment < ActiveRecord::Base<br>
  attr_accessible :post_id, :image, :remote_image_url, :document, :remote_document_url, :video, :remote_video_url<br>
  belongs_to :post<br>
  belongs_to :user<br><br>
  mount_uploader :image, ImageUploader<br>
  mount_uploader :document, DocumentUploader<br>
  mount_uploader :video, VideoUploader<br>
end<br>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shebanoff, 2012-11-23
@qweewq

Here we need to solve two problems.

1. Associate posts with the PostAttachment intermediate entity, which will allow using the attachment with different posts.

class PostAttachment < ActiveRecord::Base
  belongs_to :post
  belongs_to :attachment
end

class Post < ActiveRecord::Base
  has_many :post_attachments
  has_many :attachments, through: :post_attachments 
end

class Attachment < ActiveRecord::Base
  ...
end

2. Implement polymorphism at the Attachment itself.

You can go directly and create your own class for each type of attachment, and then use what the rail offers inside the PostAttachment. Thus, you will get a pretty practical connection of the post with N different classes.
If this method seems rough, then you can combine these N classes into one table using Single Table Inheritance , like this . The obvious plus that you get in this case is that each of the VideoAttachment, AudioAttachment, etc. classes. will be explicitly separated from the Attachment itself. Accordingly, the logic will be well separated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question