Rails`with_many through`带有不同的标签

时间:2013-09-03 11:16:23

标签: ruby-on-rails ruby has-many-through

我有以下活动记录类。我试图在不使用gem的情况下制作类似于twitter的标记。可以save_tagscreate_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

1 个答案:

答案 0 :(得分:0)

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

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

你可以预加载它们:

old_tags = Tag.where(name: tags)