Problem implementing tagging

I have a Post model, which is linked to the Tag model via a
has_and_belongs_to_many relationship and a join table. Post also has
handy
tagstring and tagstring= methods that allow you to define tags by
space-delimited strings.

The problem is this. Whether I assign a list of tags with the
tagstring=
method or use p.tags << to form the list of tags, if (on a newly-created
post) I try to assign a tag that already exists in the tags table, the
entry
won’t save in the join table. If I go back and assign it again (this
time
the Post is not a new object), it’ll work. I know acts_as_tag had a
similar
problem (the same problem?), but I can’t find anywhere that talks about
it.

Here’s my Tag and Post models (the only relevant code I could think of
posting):
class Post < ActiveRecord::Base
validates_presence_of :title, :body
has_many :comments
has_and_belongs_to_many :tags, :join_table => ‘tagmap’, :order => ‘name
asc’

def tagstring
tags.inject([]){|s,t| s << t.name}.join ’ ’
end

def tagstring=(string)

self.tags = string.split.map do|t| Tag.get(t) end

end

end

class Tag < ActiveRecord::Base
validates_presence_of :name
has_and_belongs_to_many :posts, :join_table => ‘tagmap’, :order =>
‘created_at desc’

def self.get(name)
Tag.find_or_create_by_name name
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs