【问题标题】:How to Model a multi-participant conversation system如何为多参与者对话系统建模
【发布时间】:2014-08-21 20:41:15
【问题描述】:

我是 Rails(和编程)的新手,在学习了一些教程后,我正在设计一个消息应用程序来测试我的技能。

我正在建模的情况是用户可以向 2 个以上的其他用户发送消息。这是我想出的

  • 一个对话有许多参与者(用户)和许多消息 (消息)。
  • 一个用户有很多对话和很多消息。
  • 消息属于用户(发件人 + 收件人)并属于对话。

那么 ActiveRecord 模型是:

class User < ActiveRecord::Base
  has_many :messages, :through :conversation
  has_many :conversations # or is belongs_to :conversation 
end

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

class Conversation < ActiveRecord::Base
  has_many :messages
  belongs_to :user # or is it has_many :users
end

或者我必须添加第四个界面收件箱

class Inbox < ActiveRecord::Base
  belongs_to :user
  has_many :conversations
end

我会将用户和对话模型更改为

class User < ActiveRecord::Base
  has_one :inbox
  has_many :conversations, :through :inbox
  has_many :messages, :through :conversation
end

class Conversation < ActiveRecord::Base
  belongs_to :inbox
  has_many :messages
  belongs_to :users
end

第二个选项看起来多余。 所以,是的,我对对话和用户之间的关系/关联很模糊。非常感谢所有能启发我的意见。

【问题讨论】:

    标签: ruby-on-rails ruby message rails-activerecord


    【解决方案1】:

    我认为您的第一种方法更好,但应该如下所示:

    class User < ActiveRecord::Base
      has_many :messages
      has_many :user_conversations
      has_many :conversations, through: :user_conversations
    end
    
    class Message < ActiveRecord::Base
      belongs_to :user
      belongs_to :conversation
    end
    
    class Conversation < ActiveRecord::Base
      has_many :messages
      has_many :user_conversations
      has_many :users, through: :user_conversations
    end
    
    # join table between users and conversations
    class UserConversation < ActiveRecord::Base
      belongs_to :user
      belongs_to :conversation
    end
    

    原因是一个用户可以有很多对话,而一个对话可以有很多用户。您需要创建联接表 UserConversation 以适应这种情况。

    此外,找出哪个模型应该属于另一个模型的最简单方法是询问哪个模型应该具有另一个模型的外键。具有外键belongs_to 的另一个模型。

    【讨论】:

    • 我明白你做了什么;你只抽象了用户和对话之间的部分关系。谢谢!我正在测试它。也感谢您的提示。
    • 是的,不,我仍然在 Rails 控制台上,试图正确地遍历关系。 (发件人/收件人/sent_messages/received_messages 等)是的,赞成。
    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 2018-02-10
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多