has_and_belongs_to_many,避免连接表中的重复 [英] has_and_belongs_to_many, avoiding dupes in the join table
本文介绍了has_and_belongs_to_many,避免连接表中的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组非常简单的 HABTM 模型
I have a pretty simple HABTM set of models
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
def tags= (tag_list)
self.tags.clear
tag_list.strip.split(' ').each do
self.tags.build(:name => tag)
end
end
end
现在一切正常,只是我在标签表中得到了大量重复项.
Now it all works alright except that I get a ton of duplicates in the Tags table.
我需要做什么来避免标签表中的重复(基于名称)?
What do I need to do to avoid duplicates (bases on name) in the tags table?
推荐答案
我通过创建一个 before_save 过滤器来解决这个问题.
I worked around this by creating a before_save filter that fixes stuff up.
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
before_save :fix_tags
def tag_list= (tag_list)
self.tags.clear
tag_list.strip.split(' ').each do
self.tags.build(:name => tag)
end
end
def fix_tags
if self.tags.loaded?
new_tags = []
self.tags.each do |tag|
if existing = Tag.find_by_name(tag.name)
new_tags << existing
else
new_tags << tag
end
end
self.tags = new_tags
end
end
end
它可以稍微优化以批量处理标签,也可能需要一些更好的事务支持.
It could be slightly optimised to work in batches with the tags, also it may need some slightly better transactional support.
这篇关于has_and_belongs_to_many,避免连接表中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文