我有一个Applicant
模型,它已经成为项目所有者和该项目申请者之间的地点或聊天场所.
我使用Applicant
表中的applicant.user
号推荐人来跟踪申请者.
我通过使用applicant.project.user
来跟踪项目所有者,这是Project
表中的引用(Applicant
的父级).
正如我所说的,Applicant
表也有一个Messages
的子表,Applicant
本质上是两个用户之间的聊天视图.
用户使用Devise进行管理.
申请者表中要提到的另一个字段是last_message
字段,每当用户为该Applicant
记录创建新消息时,该字段就会更新.
class Applicant < ApplicationRecord
belongs_to :project
belongs_to :user
has_many :messages, dependent: :destroy
end
class Project < ApplicationRecord
belongs_to :user
has_many :applicants, dependent: :destroy
has_rich_text :description
end
class User < ApplicationRecord
has_many :projects, dependent: :destroy
has_many :applicants, dependent: :destroy
has_rich_text :about
devise :database_authenticatable, :registerable, :confirmable, :trackable,
:recoverable, :rememberable, :validatable
end
class Message < ApplicationRecord
belongs_to :applicant
end
我想获得任何用户‘聊天’(或申请者)的列表.这既是他们的项目,也是他们的申请者.
我目前正在做这件事:
project_messages = []
current_user.projects.each do |project|
project.applicants.each do |applicant|
project_messages << applicant
end
end
@chats = Applicant
.where(id: (current_user.applicants + project_messages)
.map(&:id))
.order(last_message: :desc)
在这里,我获得了Current_User项目的列表,并将每个申请者(聊天室)添加到一个数组中.然后,我将其添加到CurrentUser.Applicers.然后,我将两者合并为活动记录关联.
这很管用,但我觉得这不是一个好办法.有谁知道做这件事更有效的方法吗?