我有以下活动记录类。我正在尝试在不使用 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