views:

3627

answers:

3

Hello.

I'm struggling now to get HATBM working correctly. I have a beaten scanario: articles and tags. I presume, HABTM should be used here, since it is a many-to-many relationship. I don't know however if I should manually create a join table (articles_tags in this case).

My code currently as follows:

class Article < ActiveRecord::Base
  has_and_belongs_to_many :tags  
end
class Tag < ActiveRecord::Base
      has_and_belongs_to_many :articles
end

When I run the migrations, no 3rd table is created. Also, I would like to add that my third table doesn't bear any domain logic, just blind assignment.

Thank you.

UPDATE: I'm using Rails 2.2.2

+25  A: 

You should do this in a migration of one of the tables, or in a separate migration if those migrations have been ran:

create_table :articles_tags, :id => false do |t|
  t.references :article, :tag
end

This will create the table for you and the :id => false tells Rails not to add an id field to this table.

You could also generate a model (ArticlesTag) for this and do:

# article.rb
has_many :articles_tags
has_many :tags, :through => :articles_tags

# tag.rb
has_many :articles_tags
has_many :articles, :through => :articles_tags

# article_tag.rb
belongs_to :tag
belongs_to :article

And then create the table in the migration generated from the script/generate model articles_tag call.

Ryan Bigg
Thanks, Radar, that's what I needed!
Valentin Vasiliev
+2  A: 

You probably also want to add an index to the migration:

add_index "articles_tags", "article_id"

add_index "articles_tags", "tag_id"

However, if you want tagging functionality I'd recommend the acts_as_taggable_on rails plugin:

http://www.intridea.com/tag/acts_as_taggable_on http://github.com/mbleigh/acts-as-taggable-on/

I've used it on a project and it was very easy to implement.

One of the issues with a join table for tagging is that it can easily get ugly creating a join table for each content type you wish to make taggable (ie. comments_tags, posts_tags, images_tags, etc). This plugin uses a taggings table which includes a discriminator to determine the content type without the need of a specific join table for each type.

Jack Chu
+1  A: 

suspected typo in first answer ...

t.references :article, :tags

should be

t.references :article, :tag
Straff