has_and_belongs_to_many,避免了连接表易受骗 [英] has_and_belongs_to_many, avoiding dupes in the join table

查看:219
本文介绍了has_and_belongs_to_many,避免了连接表易受骗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pretty的简单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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆