Ruby on rails Rails-有许多多态标记无法正常工作
我有两个标签表,这样我就可以附加标签到任何模型,它的工作原理就像这样 有一个标记项联接表,它有一个tag_id列,然后还有两个多态性列:taggable_type和taggable_idRuby on rails Rails-有许多多态标记无法正常工作,ruby-on-rails,polymorphism,has-many-through,polymorphic-associations,tagging,Ruby On Rails,Polymorphism,Has Many Through,Polymorphic Associations,Tagging,我有两个标签表,这样我就可以附加标签到任何模型,它的工作原理就像这样 有一个标记项联接表,它有一个tag_id列,然后还有两个多态性列:taggable_type和taggable_id class TaggedItem < ActiveRecord::Base attr_accessible :taggable_id, :taggable_type, :tag_id belongs_to :taggable, :polymorphic => true belongs_
class TaggedItem < ActiveRecord::Base
attr_accessible :taggable_id, :taggable_type, :tag_id
belongs_to :taggable, :polymorphic => true
belongs_to :tag
end
class TaggedItemtrue
属于:标签
结束
还有所有可以有标签的东西,例如,这里有一个带有标签的产品和图像模型:
class Product < ActiveRecord::Base
has_many :tagged_items, :as => :taggable, :dependent => :destroy
has_many :tags, :through => :tagged_items
end
class Image < ActiveRecord::Base
has_many :tagged_items, :as => :taggable, :dependent => :destroy
has_many :tags, :through => :tagged_items
end
类产品:taggable,:dependent=>:destroy
有\u多个:标记,:至=>:标记\u项
结束
类映像:taggable,:dependent=>:destroy
有\u多个:标记,:至=>:标记\u项
结束
问题在于标签模型,我似乎可以得到相反的工作,在标签模型上,我希望有很多图像和产品,如:
class Tag < ActiveRecord::Base
has_many :tagged_items, :dependent => :destroy
has_many :products, :through => :tagged_items
has_many :images, :through => :tagged_items
end
class标记:销毁
有多个:产品,:至=>:标记的\u项目
有\u多个:图像,:至=>:标记\u项
结束
这导致了一个错误,我想知道如何修复它。因此,标记表通过多态标记项表工作
任何帮助都将不胜感激。谢谢
编辑:
在模型TaggedItem中找不到源关联:product或:products。尝试“has_many:products,:through=>:taged_items,:source=>”。是:taggable还是:tag?
在设置标记与TaggedItem的关联时,不需要使用as
选项:as=>:taggable
意味着标记项上的标记是多态的,而不是多态的。相反,另一面是,即,可以标记的项目,正如您的名字巧妙地暗示的:)
class标记:销毁
有多个:产品,:至=>:标记的\u项目
有\u多个:图像,:至=>:标记\u项
结束
标签模型中的关联有很多:通过标签模型中的关联无法从标签数据项模型中获取产品
和图像
的源关联。e、 g.有多个:产品,:至=>:标记的项目
将在TaggedItem中查找直接关联属于:产品
,在多态关联的情况下,该关联写为属于:taggable,:多态=>true
。因此,为了让标记模型了解关联的确切来源,我们需要添加一个选项:source
,其类型为:source\u type
因此,将标记模型关联更改为
class Tag < ActiveRecord::Base
has_many :tagged_items, :dependent => :destroy
has_many :products, :through => :tagged_items, :source => :taggable, :source_type => 'Product'
has_many :images, :through => :tagged_items, :source => :taggable, :source_type => 'Image'
end
class标记:销毁
有多个:产品,:至=>:标记的项目,:源=>:标记的,:源类型=>“产品”
有多个:图像,:至=>:标记的项目,:源=>:标记的,:源\类型=>“图像”
结束
这将解决您的问题。:) 抛出了什么错误?你能把它寄出去吗?也就是说,当你做“一些标签产品”时会发生什么?为什么你在标签上使用多态性?因为一个TaggedItem和另一个TaggedItem之间没有关系,即在TaggedItem中;no有很多:标记的项目,:as=>:标记的关联。@Stobbej我已经指出了如果你做一些标记产品时会出现的错误
class Tag < ActiveRecord::Base
has_many :tagged_items, :dependent => :destroy
has_many :products, :through => :tagged_items
has_many :images, :through => :tagged_items
end
class Tag < ActiveRecord::Base
has_many :tagged_items, :dependent => :destroy
has_many :products, :through => :tagged_items, :source => :taggable, :source_type => 'Product'
has_many :images, :through => :tagged_items, :source => :taggable, :source_type => 'Image'
end