Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How would you store TAGS, associated with a particular record?

tags

  • Please log in to reply
2 replies to this topic

#1 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 15 September 2013 - 12:56 AM

So I have a "posts" table, and I want to associate "tags" with each post.  (Similar to Topic Tags, like on this board). 

 

Later on, users can click on a tag, and all related "posts" (i.e. with the same tag) will be displayed. 

 

What's the best/easy way to implement this?  (okay, maybe the best way ain't the easy way?) 

 

Here's what I'm thinking. 

 

METHOD A: 

Create  a "tags" table, containing post_id and tag field. 

Associate the "tags" table to my "posts" table. 

 

On the web form, user will enter all the tags in one text field.

I parse this field, and split it up using the "," as the delimeter.

Loop, store each tag found into the "tags" table. 

 

 

METHOD B:

No need to create a separate "tags" table.

Add a "tag" string field in my "posts" table. 

On the web form, user will enter all the tags in one text field. Store this text field directly to "posts" table.

Use SQL LIKE or CONTAINS to do queries on the "tag" field.  

 

 

METHOD C:

?????

 

How would you do it? Is there another more efficient way? 

 



#2 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 15 September 2013 - 08:04 AM   Best Answer

I would utilise the has_and_belongs_to_many association.

# post.rb
class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

# tag.rb 
class Tag < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

To do this, remember to create a table for the association

class CreatePostsAndTags < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.timestamps
    end
 
    create_table :tags do |t|
      t.string :name
      t.timestamps
    end
 
    create_table :posts_tags do |t|
      t.belongs_to :post
      t.belongs_to :tag
    end
  end
end

Now you can lookup the tags through the posts with Post.find(1).tags, as well as finding all the posts with a given tag with Tag.find(1).posts.


Blog: http://ohm.sh | Twitter: madsohm


#3 kany

kany

    Passenger

  • Members
  • 2 posts

Posted 09 October 2013 - 02:51 PM

I would use a Ruby gem.  Some of these gems out-of-the-box should do the job.

 

https://www.ruby-too...s/rails_tagging

 

http://railscasts.co...des/382-tagging






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users