Implementing tags in Rails: how to reference multiple elements with a single tag?

I am writing a blog engine in rails, and have set up a tag model and a post model that has has_and_belongs_to_many relationships. Adding a tag works fine, the problem occurs when searching for all posts with a specific tag:

If I add the β€œtest” tag to Post A, add the β€œtest” tag to publish B, there are two tag objects, both with the name β€œtest”, but with different identifiers, both refer to different messages. Now, if I have an actionTagPosts controller that accepts the "tag" parameter and finds all messages with this tag, it will return only one message, since the other tag has a different identifier and is not actually connected. Should I somehow limit the addition of new tags, or should I manipulate how I pull all the relevant tags differently?

Here is a controller action that should capture all relevant messages based on the 'tag' parameter:

def indexTagPosts

        @tag = Tag.find(params[:tag])
        @posts = @tag.posts.all

end

And here is the action to save the tag:

def create


    @post = Post.find(params[:post_id])
    @tag = @post.tags.create(params[:tag])

    respond_to do |format|
      if @tag.save
        format.html { redirect_to edit_post_path(@post),:notice => "Success" }
      end
    end  

end

Thanks in advance and apologies for the redundancy or poor wording.

+5
1

, has_and_belongs_to_many, , . , has_many ..., :through, .

, , , , :

class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => :post_tags
end

class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, :through => :post_tags
end

class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag
end

:

@post = Post.find(params[:post_id])

if (params[:tags].present?)
  @post.tags = Tag.where(:name => params[:tags].split(/\s*,\s*/))
else
  @post.tags = [ ]
end

has_many , PostTag .

, Post, , :

 class Post
   def tags_used
     self.tags.collect(&:name).join(',')
   end

   def tags_used=(list)
     self.tags = list.present? ? Tag.where(:name => list.split(/\s*,\s*/)) : [ ]
   end
 end
+9

All Articles