:polymorphic/:through ActiveRecord associations (Rails 3.2) -


i have tag system can apply various taggables. want able query them transparently, in accepted solution here:

habtm polymorphic relationship

i want able say, example, show me posts, pages, videos, etc. tagged 'foo'. pretty straighforward. complications:

  1. the different kinds of taggables not polymorphic in oo sense, through polymorphic associations. there is taggables table guarantee uniqueness of taggable_id (the primary key in posts, etc.).
  2. tags, not surprisingly, have many-to-many relation taggables, , associated through map_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:

  1. 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...
  2. did set polymorphism correctly? understanding "child" models declare "tagged", , whichever table interfaces them directly (in case map_tags) 1 :polymorphic declaration.
  3. 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

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -