I'm having difficulty wrapping my mind around the necessary associations for the following situation:
I have an "upload" which can be attached to either a "person", a "group", a "project", or an "office".
An upload needs to belong to multiple people, groups, or projects at the same time (ie: It can be linked to two people, three projects, one group, two offices.)
A person, a project, a group, or a project can have multiple uploads associated with them.
I'd like to be able to grab all the Uploads associated with an object (ex: @project.uploads), and also all the items an upload is linked to (in a single method, such as @upload.linked_to)
I am trying to avoid creating a table for each possible association (projects_uploads, people_uploads, offices_uploads) as I would like it to be more flexible since there might be other models I would like to link uploads to in the future.
A polymorphic association might be what I need... but I haven't found an example that is quite like what I'm trying to accomplish.
Can somebody point me in the right direction?
Thank you! I can attempt to clarify my question if necessary :)
EDIT: Solved! This is how I ended up setting it up:
MODELS
Upload.rb
class Upload < ActiveRecord::Base
has_many :upload_connections
def linked # Shortcut for @upload.upload_connections
self.upload_connections
end
end
Upload_connection.rb
class UploadConnection < ActiveRecord::Base
belongs_to :uploadable, :polymorphic => true
belongs_to :upload
end
Project.rb / Office.rb / Person.rb etc.
class Project < ActiveRecord::Base
# (same for project, office, person, etc.)
has_many :upload_connections, :as => :uploadable
has_many :uploads, :through => :upload_connections
end
TABLE STRUCTURES
Uploads
id: integer
filename: string
description: string
Upload_connections
id: integer
uploadable_id: integer
uploadable_type: string
upload_id: integer
... plus the tables for whatever objects you want to associate them with.