![](/img/trans.png)
[英]ActiveRecord, has_many :through, and Polymorphic Associations
[英]:polymorphic/:through ActiveRecord associations (Rails 3.2)
我有一个可以应用于各种Taggable
的标签系统。 我希望能够透明地查询它们,如此处接受的解决方案中所示:
例如,我想告诉我所有带有'foo'标签的Post
, Page
, Video
等等。 很直率的。 并发症:
Taggable
并不是多态的,仅通过多态关联。 有一个taggables
表,以保证taggable_id的唯一性(在主键posts
等)。 Tag
与Taggable
具有Taggable
关系,并且通过map_tags
表关联。 楷模:
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 are set up similarly
end
问题:
map_tags
)都是获得:polymorphic
声明的表。 我尝试过的
irb> Tag.find_by_name( 'foo', :include => :tagged )
Tag Load (0.1ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`name` = 'foo' LIMIT 1
NameError: uninitialized constant Tag::Tagged
...
irb> Tag.find( :all, :include => :tagged, :conditions => ["Tag.name = 'foo'"] )
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:
Cannot have a has_many :through association 'Tag#tagged' on the polymorphic object 'Tagged#tagged'.
...
编辑
我发现了这篇文章 ,指出我需要指定:source
和:source_type
。 所以:
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
我想我离(?)越来越近,但是我仍然不确定如何查询关联的对象...
irb> Tag.first.posts
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` LIMIT 1
NoMethodError: undefined method `posts' for #<Tag id: 1, name: "foo">
irb> Tag.first.tagged
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` LIMIT 1
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:
Cannot have a has_many :through association 'Tag#tagged' on the polymorphic object 'Tagged#tagged'.
您的多态关联设置正确。 除了一个小的错别字:
belongs_to :tagged, :polymorphic => :true
布尔值应该为true,而不是:true符号!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.