satynos
2009-Feb-10 16:02 UTC
How to achieve STI has_many :through referencing to the same STI
I have the base Content model from which all the types of the contents such as page, post, asset descend as follows: class Content < ActiveRecord::Base end class Page < Content end class Post < Content end class Asset < Content end Now I am trying to accomplish relationships between all these contents using a relationship table as follows: class Relationship < ActiveRecord::Base belongs_to :content, :polymorphic => true belongs_to :target, :polymorphic => true end Accordingly I updated the base models to reflect the relationships as follows: class Page < Content has_many :relationships, :as => :content has_many :posts, :through => :relationships, :source => :target, :source_type => "Post" has_many :assets, :through => :relationships, :source => :target, :source_type => "Asset" end class Post < Content has_many :relationships, :as => :content has_many :pages, :through => :relationships, :source => :target, :source_type => "Page" has_many :assets, :through => :relationships, :source => :target, :source_type => "Asset" end class Asset < Content has_many :relationships, :as => :content has_many :pages, :through => :relationships, :source => :target, :source_type => "Page" has_many :posts, :through => :relationships, :source => :target, :source_type => "Post" end But when I try to access @page.assets, I am getting empty array. In looking at the log file, I see the reason being the following query: SELECT `contents`.* FROM `contents` INNER JOIN relationships ON contents.id = relationships.target_id <b>AND relationships.target_type = ''Asset''</b> WHERE (`relationships`.content_id = #{id} ) AND (`contents`.`type` ''Asset'') The problem is due to the highlighted portion of the query. When the active record saves a relationship, it is saving the content_type and target_type as "Content" (the base model class) instead of the actual content type "Page" or "Post" or "Asset". Is there any way possible to achieve what I am trying without any plugins? How can I tell ActiveRecord to save the content_type and target_type of the relationship with the actual class name instead of the base class name? BTW: I looked into has_many_polymorphs, but it doesn''t quite solve my problem. Thanks in advance. -Satynos --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---