logesh
logesh

Reputation: 2662

How to add additional attributes to the join table in HABTM and fetch that when getting association values?

I have two models User and Category. Consider the following code

class User < ActiveRecord::Base
    has_and_belongs_to_many :categories
    accepts_nested_attributes_for :categories, :allow_destroy => true
    alias_method :categories=, :categories_attributes=
end

and

class Category < ActiveRecord::Base
    has_and_belongs_to_many :users
end

I want to create categories when it is not already present in the category table. If the category is already present in the table then i need to refer the id of the category to the user in the join table. And consider i need to add a field say type in the join table along with the reference where i need to add the type of the category.

Say for example

user table:

1, sample_user
2, test_user

and

category table:

1, category1
2, category2

and

categories_users:

category_id               user_id       type
      1                     1            type1
      2                     1            type2
      1                     2            type2
      1                     2            type1

And when getting the category of users i need to get the category object along with the type of the category within the category object.

How can i do this? please help me

Upvotes: 0

Views: 729

Answers (1)

Frost
Frost

Reputation: 11957

If you want attributes on the join table in a HABTM association, you should probably look into making the join table a separate model, and using has_many :through instead.

In this case, that would yield something like this:

class User < ActiveRecord::Base
  has_many :categories, through: :user_categories
end

class Category < ActiveRecord::Base
  has_many :users, through: :user_categories
end

class UserCategory < ActiveRecord::Base # or whatever you want to call it
  belongs_to :user
  belongs_to :category
end

Upvotes: 2

Related Questions