has_and_belongs_to_many, avoiding dupes in the join table

前端 未结 12 1015
南旧
南旧 2020-12-04 11:07

I have a pretty simple HABTM set of models

class Tag < ActiveRecord::Base 
   has_and_belongs_to_many :posts
end 

class Post < ActiveRecord::Base 
           


        
12条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 11:47

    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.

提交回复
热议问题