views:

397

answers:

1

Hi gys i am trying to link two entities to one entity which is governing body, estate and repo_document, then a governing body can have repo_document that the estate can also have so i decided to create a join table named document_owner.. but i dont know what to write in their models..i have got this code in my document_owner model..

belongs_to :repo_document
belongs_to :estate, :through => :repo_document, :foreign_key => :owner_id, :conditions => "owner_type = 'Estate'"
belongs_to :governing_body, :through => :repo_document, :foreign_key => :owner_id, :conditions => "owner_type = 'GoverningBody'"
belongs_to :owner, :polymorphic => true

and this one in my repo_document

 has_and_belongs_to_many :owners, :join_table => :document_owners, :conditions =>     "owner_type = 'Estate' OR owner_type = 'GoverningBody'"

and this one in my estate

has_many :repo_documents, :source => :document_owners, :foreign_key => :owner_id, :conditions => "owner_type = 'Estate' "

and this one in my governing_body

has_many :repo_documents, :source => :document_owners, :foreign_key => :owner_id, :conditions => "owner_type = 'GoverningBody' "

but when i try to save it does not save anything inside the join table..

can anybody help me please

+1  A: 

Just as advice, I think polymorphic join tables are a really bad idea and should be avoided except when strictly necessary. Not only are they very difficult to index correctly, but they will make every query involving them a few degrees more complicated and that much harder to scale. Ideally any polymorphic associations you have will never be used to join two tables together.

Further, use of has_and_belongs_to_many is deprecated, were the use of has_many :through is a much better solution in most situations.

One way to simplify this is to combine your Estate and GoverningBody models into a single table, perhaps using STI to distinguish between the two. That way the relationship between documents and this particular entity is much more obvious.

If that's not practical, then you may be better off having two straightforward join tables rather than a polymorphic one.

Polymorphic associations are best for somewhat casual relationships that are one to many. For example:

class Example < ActiveRecord::Base
  # This model has notes
  has_many :notes, :as => :record
end

class Note
  # Can be attached to any kind of record
  belongs_to :record, :polymorphic => true
end

In this case, a Note is something that can be attached to any kind of record. Importantly, it is not used in the middle of a relationship, it is an end-point.

tadman