Modelling image/media files in a Rails app

Anyone up for talking about how to design a model for image uploads? I am exploring ways to model image/media uploads (in a Rails context). I want to do it in a flexible manner though, such that images can be associated with multiple resources. (I think the most challenging way to think about this is a slide/presentation context, where a single slide can have multiple images, but the image doesn’t belong to a slide per se, (the same image can be associated with multiple slides, slideshows, or even appear on a single slide multiple times. i don’t have a specific product in mind…but I am enjoying the thought experiment.

I would love to explore how different projects have approached this sort of problem.

Thanks,

Dave

I know this is an old question, but since you didn’t get any replies, I thought I would chime in.

In your slides example, it’s clear that a Slide can be associated with more than one Image, and Image can be associated with more than Slide. As a result, you need a many-to-many relationship.

In Rails, many-to-many relationships are often implemented as a “has_many through” relationship, which links one record to another via an intermediate record.

As an example, you could have a SlideImageAssignment model, which connects a given Slide to a given Image.

class SlideImageAssignment < ActiveRecord::Base
  belongs_to :slide
  belongs_to :image
end

class Slide < ActiveRecord::Base
  has_many :slide_image_assignments
  has_many :images, through: :slide_image_assignments
end

For each image you want to associate with a slide, you create a separate SlideImageAssignment record.

1 Like