Help with tricky object relations


#1

In a document management system I’m building each document belongs to
a company and a department in that company. So far so good, but the
problem is that a single document can also belong to multiple
companies and departments.

What I would like to do is to have different pages with links to
documents for each company and on those pages divide them under the
departments.

What is the best way to handle a situation like this?

My initial thinking is to only link the document to the departments
because the department has a child relationship to the company. But
then the code to get all documents for a specific company seems to get
quite convoluted.

Any insights on how to structure this would be most welcome.


#2

Am Sonntag, den 26.02.2006, 23:40 -0800 schrieb Jens Norrgrann:

My initial thinking is to only link the document to the departments
because the department has a child relationship to the company. But
then the code to get all documents for a specific company seems to get
quite convoluted.

Any insights on how to structure this would be most welcome.

class Document < ActiveRecord:Base
end

class Department < ActiveRecord:Base
has_and_belongs_many :documents
belongs_to :company
end

class Company < ActiveRecord:Base
has_many :departments

def documents
departments.collect { |department|
department.documents }.flatten.uniq
end
end

In edge Rails the new :through relationship option is introduced, what
might be a simpler solution, but has the same effect.


Norman T.

http://blog.inlet-media.de