0

我有以下活动记录类。我正在尝试在不使用 gem 的情况下制作类似于 twitter 的标签。可以save_tags进一步create_tags优化吗?

class Opinion < ActiveRecord::Base
  belongs_to :user      
  has_many :taggings
  has_many :tags, through: :taggings
  after_create :save_tags

  def self.tagged_with(name)
    Tag.find_by!(name: name).opinions
  end

  private

    def save_tags
      tags = create_tags      
      tags.each do |tag|
        t = tag.downcase
        oldTag = Tag.find_by(name: t)
        if oldTag
          tagging = Tagging.new(opinion: self, tag: oldTag)
          tagging.save
        else
          self.tags.create(name: t)
        end
      end
    end

    def create_tags
      tags = self.about.scan(/(\#{1}[a-zA-Z1-9]*\b)/).flatten
      if tags
        tags.uniq.reject! { |tag| tag.length < 2 }       
      end 
      return tags
    end
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :opinions, through: :taggings
  validates_uniqueness_of :name
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :opinion
end
4

1 回答 1

0

此代码调用 tags.count 数据库查询:

tags.each do |tag|
  t = tag.downcase
  oldTag = Tag.find_by(name: t)
  ...
end

您可以预加载它们:

old_tags = Tag.where(name: tags)
于 2013-09-03T11:26:34.290 回答