:polymorphic/:through ActiveRecord associations (Rails 3.2) -
i have tag system can apply various taggable
s. want able query them transparently, in accepted solution here:
habtm polymorphic relationship
i want able say, example, show me post
s, page
s, video
s, etc. tagged 'foo'. pretty straighforward. complications:
- the different kinds of
taggable
s not polymorphic in oo sense, through polymorphic associations. there istaggables
table guarantee uniqueness of taggable_id (the primary key inposts
, etc.). tag
s, not surprisingly, have many-to-many relationtaggable
s, , associated throughmap_tags
table.
models:
class tag < activerecord::base has_many :map_tags has_many :tagged, :through => :map_tags end class maptag < activerecord::base belongs_to :tags belongs_to :tagged, :polymorphic => :true end class post < activerecord::base has_many :map_tags, :as => :tagged has_many :tags, :through => :map_tags # other taggables set end
questions:
- i guess first questions ought be: possible? have seen models "have many" associated instances polymorphically, i'm not sure if works other way, error message below may suggest...
- did set polymorphism correctly? understanding "child" models declare "tagged", , whichever table interfaces them directly (in case
map_tags
) 1:polymorphic
declaration. - how "show me tagged 'foo'" in activerecord-speak?
what i've tried:
irb> tag.find_by_name( 'foo', :include => :tagged ) tag load (0.1ms) select `tags`.* `tags` `tags`.`name` = 'foo' limit 1 nameerror: uninitialized constant tag::tagged ... irb> tag.find( :all, :include => :tagged, :conditions => ["tag.name = 'foo'"] ) activerecord::hasmanythroughassociationpolymorphicsourceerror: cannot have has_many :through association 'tag#tagged' on polymorphic object 'tagged#tagged'. ...
edit
i found this post, points out need specify :source
, :source_type
. so:
class tag < activerecord::base has_many :map_tags has_many :posts, :through => :map_tags, :source => :tagged, :source_type => 'post' has_many :pages, :through => :map_tags, :source => :tagged, :source_type => 'page' end
i think i'm closer(?), i'm still not sure how query associated objects...
irb> tag.first.posts tag load (0.2ms) select `tags`.* `tags` limit 1 nomethoderror: undefined method `posts' #<tag id: 1, name: "foo"> irb> tag.first.tagged tag load (0.2ms) select `tags`.* `tags` limit 1 activerecord::hasmanythroughassociationpolymorphicsourceerror: cannot have has_many :through association 'tag#tagged' on polymorphic object 'tagged#tagged'.
your polymorphic association setup correct. except small typo :
belongs_to :tagged, :polymorphic => :true
it should true boolean not :true symbol !
Comments
Post a Comment