Topic: Tricky Association Setup

Hi All,

If anyone had a couple of recommendations I would certainly be interested to hear how you might go about this.

Trying to set up an internal messaging/task system for a web app.

So basically a User can Send a Message/Task to be Received by another User.
I was trying to create an association that would allow for two has_many :through relationships.
I wanted to allow a user to send a message to another user or many users but then also that person can forward on the message and become a sender.  I was thinking of sender and receiver as two channels / sets of data.

The code that I did have..

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :senders
  has_many :tasks, :through => :senders

  has_many :receivers
  has_many :tasks, :through => :receivers
end


class Task < ActiveRecord::Base

  attr_accessible :title, :body, :location, :start_time, :end_time, :system_id, :task_type_id

  has_many :senders
  has_many :users, :through => :senders

  has_many :receivers
  has_many :users, :through => :receivers

  validates :system_id, :presence => true
  validates :task_type_id, :presence => true
end



class Sender < ActiveRecord::Base
  attr_accessible :user_id, :task_id, :sent, :sent_time
  belongs_to :user
  belongs_to :task
end

class Receiver < ActiveRecord::Base
  attr_accessible :user_id, :task_id, :read, :completed, :opened_time, :read_time, :replied_time, :completed_time
  belongs_to :user
  belongs_to :task
end

I couldn't figure out how to tell rails which avenue to get to tasks from.. ideally I would be able to use

User.sender.tasks
User.receiver.tasks

Or a very similar notation.  Changing to a single has_many :through relationship with a type field isn't working the way I was hoping to either.

Thanks for any thoughts.

Re: Tricky Association Setup

I dont understand why you set up your relationships like you did hmm

IMO a better solution would be a simple 1:n relation:

User has_many messages
Message belongs_to User

=> The owner of the messages is the sender, the recievers could be an array of user.ids in Message

If another user wants to forward the message, create a new message for the forwarding user and copy the content plus whatever you need from the old message.