views:

230

answers:

3

My Example:

class Category < ActiveRecord::Base
  has_many :tags, :as => :tagable, :dependent => :destroy

  def tag_string
    str = ''
    tags.each_with_index do |t, i|
      str+= i > 0 ? ', ' : ''
      str+= t.tag
    end
    str
  end

  def tag_string=(str)
    tags.delete_all
    Tag.parse_string(str).each { |t| tags.build(:tag => t.strip) }
  end

end

How would you optimize this tag_string field? I don't want to delete all the tags every time I would like to just update them. Is there a better way to parse string with tags? I do not want use a plugin! Thx.

+2  A: 

I know you don't want to use a plugin, but you might want to dig through the source of acts_as_taggable_on_steroids to see how they're handling these situations. From my experience, working with that plugin has been very painless.

jerhinesmith
+1  A: 
class Category < ActiveRecord::Base
  has_many :tags, :as => :tagable, :dependent => :destroy

  def tag_string
    tags.map {|t| t.name }.join ', '
  end

  def tag_string=(str)
    tags = Tag.parse_string(str)
  end

end

I don't know what Tag.parse_string(str) method do. If it returns an array of Tag objects, than my example should work. And I'm not sure if this will only update, or delete old and add new one. You can test it and look in logs what it really does.

klew
+1  A: 

I agree with other commenters. You are better off using the plugin here. Here is one solution.

 class Category < ActiveRecord::Base
  has_many :tags, :as => :tagable, :dependent => :destroy

  def tag_string
    tags.collect(&:name).join(", ")
  end

  def tag_string=(str)
    # Next line will delete the old association and create
    # new(based on the passed str). 
    # If the Category is new, then save it after the call.
    tags = Tag.create(str.split(",").collect{ |name| {:name => name.strip} })
  end

end
KandadaBoggu
I don't thing tag_string=(str) will do do trick. Am I wrong?
xpepermint
I have changed the answer. It should work.
KandadaBoggu