Topic: Multiple Models has_many of the Same Model

I want a model (File) that will allow multiple other models (Order, Task, Message, etc ...) to each have many Files. Is this possible?

If so:
A) What concepts are involved so I can research them and see if I can't get there myself.
B) What is the answer and I can reverse engineer it myself.

I am not necessarily looking for someone to say: "Here is the code, have a nice day!" If that happens fine, however, I am just as happy to have someone point me in the right direction (concepts, key words, etc) so that I might arrive at the answer myself. Almost like learning. big_smile

In my mind the models look a bit like this:

class File < ActiveRecord::Base
  # carrier_wave stuff
end

class HasManyFiles < ActiveRecord::Base
  self.abstract_class = true
  has_many :files
end

class Order < HasManyFiles
end

class Task < HasManyFiles
end

class Message < HasManyFiles
end

I want to be able to use it like this:

  all_files = File.all
  all_order_files = Order.find(1).files

What columns the tables need to have to achieve this...I do not know!

Last edited by rlovelett (2011-06-01 14:56:10)

Re: Multiple Models has_many of the Same Model

Yes, you want polymorphic associations (but choose a diffrent name for the file model, it's a reserved word)
There is a good railscast on this
http://railscasts.com/episodes/154-poly … ssociation

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)