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
AND relationships.target_type = ‘Asset’
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