1

我有一个包含三个模型的标记系统:Person (People)TagTagging

我希望能够同时标记人员和标签(所以标记标签)

Person和的模型Tagging似乎是正确的:

class Person < ActiveRecord::Base

 #associations
 has_many :taggings, as: :taggable
 has_many :tags, through: :taggings

end


class Tagging < ActiveRecord::Base

 attr_accessible :taggable_id, :taggable_type

 #associations
  belongs_to :tag
  belongs_to :taggable, polymorphic: true

 end

所以我能够做到<Person_instance>.tags并获得正确的标签。

问题来自标签。我尝试了以下方法:

class Tag < ActiveRecord::Base
  attr_accessible :name

  has_many :taggings
  has_many :tags, through: :taggings, source: :taggable, source_type: :'Tag'

  has_many :people, through: :taggings, source: :taggable, source_type: :'Person'

end

使用此设置,标签仍然能够标记其他标签,但模型会翻转标记了哪个标签。例如,如果我正在搜索 Tag.id == 10 的标签,那么 SQL 应该搜索 taggable_id = 10,而不是 tag_id,如下所示:

Tag.find(10).tags
Tag Load (0.4ms)  SELECT `tags`.* FROM `tags` WHERE `tags`.`id` = 10 LIMIT 1
Tag Load (0.4ms)  SELECT `tags`.* FROM `tags` INNER JOIN 
 `taggings` ON `tags`.`id` = `taggings`.`taggable_id` 
  WHERE `taggings`.`tag_id` = 10 AND `taggings`.`taggable_type` = 'Tag'

这适用于 Person,其中 SQL 搜索taggable_id

Person.find(:last).tags
Person Load (0.4ms)  SELECT `people`.* FROM `people` ORDER BY `people`.`id` DESC LIMIT 1
Tag Load (0.4ms)  SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON 
 `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 3 
 AND   `taggings`.`taggable_type` = 'Person'

关于如何标记标签的想法将不胜感激!谢谢你。

4

0 回答 0