Forum: Ruby on Rails Problem implementing tagging

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5316d692cc603c3ad2df0f03869bb96b?d=identicon&s=25 Mik Mifflin (Guest)
on 2006-01-06 00:18
(Received via mailing list)
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 topic is locked and can not be replied to.