HABTM on 3 tables


#1

Hi. Currently, I had 2 models linked with HABTM association: Article
and Tag

class Article < ActiveRecord::Base
has_and_belongs_to_many :tags
end

class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles
end

But I believe I need to ad another model called User. Do you know how
processed to get a HABTM association with: Article, Tag and User?

Thx


#2

just an information to be more clear:
I had yet created a table called “articles_tags_users” in the database.


#3

Am 24.10.2008 um 16:23 schrieb Panda B.:

just an information to be more clear:
I had yet created a table called “articles_tags_users” in the
database.

I think you are looking for something like this:

http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids


Jochen


#4

Panda B. wrote:

But I believe I need to ad another model called User. Do you know how
processed to get a HABTM association with: Article, Tag and User?

Perhaps by creating a Hub model with three foreign keys, and
using has_many through.


Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com


#5

YES! I found the answer:

class Article < ActiveRecord::Base
has_and_belongs_to_many :tags, :join_table => :articles_tags_users
has_and_belongs_to_many :users, :join_table => :articles_tags_users
end

class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles, :join_table => :articles_tags_users
has_and_belongs_to_many :users, :join_table => :articles_tags_users
end

class User < ActiveRecord::Base
has_and_belongs_to_many :articles, :join_table => :articles_tags_users
has_and_belongs_to_many :tags, :join_table => :articles_tags_users
end

have fun!


#6

Jochen K. wrote:

I think you are looking for something like this:
http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids

I think this solution is a little bit so specific and so complexe for my
association need. I hope there is a more simple way include by defaut in
ActiveRecord.

Mark Reginald J. wrote:

Perhaps by creating a Hub model with three foreign keys, and
using has_many through.

In my context, I prefer using only 3 models with a HABTM association
rather than using 4 models with some has_many through.

Thanks for your ideas.


#7

Some help please!

How do you fill the table with the three foreign keys??
i put
user = User.new
tag = Tag.find(id)
article = Article.find(id)
user.tag << tag
user.article << article

user.save

all this creates 2 tuples on the database articles_tags_users instead of
one
with all the values

On Sat, Oct 25, 2008 at 6:02 AM, Panda B. <
removed_email_address@domain.invalid> wrote:

has_and_belongs_to_many :users, :join_table => :articles_tags_users


Felipe V. Contesse
Ingeniería Civil Industrial UC