kanekcwu
kanekcwu

Reputation: 125

Adding another attribute to a many-to-many table in rails 3

I am currently using has_and_belongs_to_many to implement a many-to-many relationship. I would however want to put in a attribute in the many_to_many table.

Basically I am creating a email system. I have users and conversations. A user can have many conversations and a conversations can also have many users. However, I am trying to make it so that I can have a read/unread attribute to show which messages are read. Since conversations can have many users, it is not practicable to put the attribute in the conversations table as then it would mean that the conversation is read by all. So I think it would work best in the middle table. I am wondering though how I can access that attribute in the middle table. If the attribute is read. What code do I put in to access that and how do I update the attribute. As mention above I am using has_and_belongs_to_many

Upvotes: 3

Views: 2147

Answers (1)

mliebelt
mliebelt

Reputation: 15525

If you want to have additional attributes to your has-and-belongs-to-many association, you have to build a model class for that relation. See the detailed description in the Rails Guides about it.

After having read it for myself, this is now deprecated with the current version of Rails, so you really should switch to has_many :through. Your models could be (copied and changed from the Rails Guides, I don't know if connection is a good name for the m2n relation):

class User < ActiveRecord::Base
  has_many :connections
  has_many :conversations, :through => :connections
end

class Connection < ActiveRecord::Base
  belongs_to :user
  belongs_to :conversation
end

class Conversation < ActiveRecord::Base
  has_many :connections
  has_many :users, :through => :connections
end

There you are able to add additional attributes to your connections table, and refer in the code to them.

Upvotes: 6

Related Questions