Need help with polymorphic rails joining table

Hello i am trying to link two entities with one object which is governing body, property and repo_document then governing body can have repo_document which manor can also have, so i decided to create a join table named document_owner .. but i dont know, what to write in your models. I have 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 is on my estate

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

      

and this one is in my reign_

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

      

but when I try to save it, it doesn't save anything inside the join table.

can someone help me please

+2


source to share


1 answer


As a tip, I think polymorphic join tables are a very bad idea and should be avoided unless strictly necessary. Not only are they very difficult to index correctly, but they will make every query they involve several degrees more complex and harder to scale. Ideally, any polymorphic associations you have will never be used to join two tables.

Also, the use of has_and_belongs_to_many is deprecated, the use of has_many: via this is a much better solution in most situations.

One way to simplify this is to combine the Estate and GlyingBody models into one table, perhaps using STI to differentiate between the two. Thus, the relationship between documents and this particular entity is much more obvious.

If this is not practical, you might be better off having two simple join tables rather than polymorphic ones.



Polymorphic associations are best for multiple casual relationships that are the same for 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 bound to any post type. It is important to note that it is not used in the middle of a relationship, it is the end point.

+4


source







All Articles