我的标记系统包含三个模型:Person (People)
,Tag
和Tagging
。
我希望能够标记人物和标签(因此标记标签)
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'
如何标记标签的想法将不胜感激!谢谢。