Gandalf StormCrow
Gandalf StormCrow

Reputation: 26192

Many to many relation with an extra column rails

I've got two players engaging a single activity and they exchange messages during that time, since many players play on many activities with other players, I started to work on a message archiving feature, and I'm having some issues about the design, since I want to archive per activity.

In my message model every message has an activity_id field.

My user model :

has_many :sent_messages, :foreign_key => 'sender_id', :class_name => Message
has_many :received_messages, :foreign_key => 'receiver_id', :class_name => Message

My archived_message :

  belongs_to :user, :class_name => User
  belongs_to :message, :class_name => Message
  attr_accessible :activity_id

And I've just added tried to add this to my model :

has_many :activity_archived_messages, :through => :archived_messages, :source => :message

Now this is the part I've been struggling a bit, because I want to archive both received and sent messages if they belong to the same activity.

How do I do that?

Upvotes: 0

Views: 137

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

You could add an Activity to your model, and then archive that:

class Activity < ActiveRecord::Base
  has_and_belongs_to_many :messages
  has_and_belongs_to_many :participants, class_name: User
end

Now, you can archive this, and have all the related messages, in both directions, saved in your archive.

Upvotes: 1

Related Questions