Rails:如何存储聊天对话



我正在编写一个rails应用程序,其中包含客户端和管理员之间的对话。我希望管理员对客户发送的问题做出回应。

管理员应该能够通过回复框查看以前的对话。

保存这些掩盖的最佳方法是什么:

  • 带有问答标记的单个表,并将其作为表条目查看
  • 不同的桌子,简单地按时间组织
class Administrator < ActiveRecord::Base
  has_many :messages, as: :author
end
class Client < ActiveRecord::Base
  has_many :messages, as: :author
end
class Message < ActiveRecord::Base
  belongs_to :author, polymorphic: true
  belongs_to :chat
end
class Chat < ActiveRecord::Base
  has_many :messages
  belongs_to :client
  belongs_to :administrator
end

如果你想显示特定聊天的消息,你可以这样做:

@chat = Chat.find_by_client_id_and_administrator_id(client_id, administrator_id)
@messages = @chat.messages.order(:created_at)

如果clientadministrator属于同一个模型,例如User,则:

class User < ActiveRecord::Base
  has_many :messages
end
class Message < ActiveRecord::Base
  belongs_to :user
  belongs_to :chat
end
class Chat < ActiveRecord::Base
  has_many :messages
  belongs_to :client, class_name: "User"
  belongs_to :administrator, class_name: "User"
end

最新更新