Rails threaded private messaging

前端 未结 1 1374
悲&欢浪女
悲&欢浪女 2021-02-01 11:17

I have the following two models:

class Message < ActiveRecord::Base
  belongs_to :to_user, :class_name => \'User\'
  belongs_to :from_user, :class_name =&g         


        
相关标签:
1条回答
  • 2021-02-01 11:47

    You may be better off restructuring this as a conversation to which you can join people than a series of interconnected messages in a chain. For instance:

    class Conversation < ActiveRecord::Base
      has_many :messages
      has_many :participants
      has_many :users, :through => :participants
    end
    
    class Message < ActiveRecord::Base
      belongs_to :conversation
    end
    
    class Participant < ActiveRecord::Base
      belongs_to :conversation
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_many :conversations
      has_many :participants
    end
    

    When a message is sent to someone, create a conversation for it and invite the appropriate parties by adding them to the users list.

    Threaded messaging could be added here by building a parent relationship into the Message itself or using ancestry, though in practice this tends to be over-kill as simple chronological ordering of replies is usually sufficient for most people.

    To track read/unread status you will need an association table between user and messages directly, and this can be tricky, so avoid it unless you need it.

    Keep in mind that some names are reserved by either Ruby or Rails, and Thread is one of them, so you can't have a model with that name.

    0 讨论(0)
提交回复
热议问题