繁体   English   中英

:polymorphic /:通过ActiveRecord关联(Rails 3.2)

[英]:polymorphic/:through ActiveRecord associations (Rails 3.2)

我有一个可以应用于各种Taggable的标签系统。 我希望能够透明地查询它们,如此处接受的解决方案中所示:

HABTM多态关系

例如,我想告诉我所有带有'foo'标签的PostPageVideo等等。 很直率的。 并发症:

  1. 从OO的角度来看,不同种类的Taggable并不是多态的,仅通过多态关联。 一个taggables表,以保证taggable_id的唯一性(在主键posts等)。
  2. 毫不奇怪, TagTaggable具有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

问题:

  1. 我想我的第一个问题应该是:这是否可能? 我已经看到模型具有多态的“具有许多”关联实例,但是我不确定它是否可以以其他方式起作用,因为以下错误消息可能会提示...
  2. 我是否正确设置了多态性? 我的理解是,“子”模型基本上将自己声明为“标记”,而直接与它们连接的任何表(在本例中为map_tags )都是获得:polymorphic声明的表。
  3. 我怎么说在ActiveRecord中说“给我看所有标有'foo'的东西”?

我尝试过的

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM