Ruby on rails 有许多通过:、多态和自引用
我有一个带有三个模型的标签系统:人物、标签和标签 我想能够标记人物和标签,所以标记标签 人物和标签的模型似乎是正确的:Ruby on rails 有许多通过:、多态和自引用,ruby-on-rails,activerecord,polymorphic-associations,Ruby On Rails,Activerecord,Polymorphic Associations,我有一个带有三个模型的标签系统:人物、标签和标签 我想能够标记人物和标签,所以标记标签 人物和标签的模型似乎是正确的: class Person < ActiveRecord::Base #associations has_many :taggings, as: :taggable has_many :tags, through: :taggings end class Tagging < ActiveRecord::Base attr_accessible :ta
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,其中SQL搜索标记id:
关于如何标记标签的想法将不胜感激!谢谢。标记模型中未定义标记。您是否尝试过Have_多:taggings和Have_多:taggings,如::taggable?
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.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.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'