我有一个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项目的列表,并将每个申请者(聊天室)添加到数组中。然后将其添加到current_user. applicants。然后,我将两者合并为一个活动记录关联。
这是可行的,但我觉得这是一个糟糕的方法。有谁知道更有效的方法吗?
2条答案
按热度按时间7vhp5slm1#
您可以加入申请人和项目表,并检查当前用户是否是申请人或项目“所有者”,如下图所示
qltillow2#
你可以跳过循环,在User模型中添加一个自定义关联,
然后你可以查询所有的聊天记录,