ruby Rails 7,返回两个独立条件的活动记录关联,一个在父级,一个在子级

wswtfjt7  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(71)

我有一个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。然后,我将两者合并为一个活动记录关联。
这是可行的,但我觉得这是一个糟糕的方法。有谁知道更有效的方法吗?

7vhp5slm

7vhp5slm1#

您可以加入申请人和项目表,并检查当前用户是否是申请人或项目“所有者”,如下图所示

applicants =
  Applicant
    .joins(:project)
    .where('applicants.user_id = :id OR projects.user_id = :id', id: current_user.id)
    .order(last_message: :desc)
qltillow

qltillow2#

你可以跳过循环,在User模型中添加一个自定义关联,

class User
  has_many :other_chats, through: :projects, class_name: "Applicant"
end

然后你可以查询所有的聊天记录,

@chats = Applicant
  .where(id: (current_user.applicants + other_chats)
  .map(&:id)).order(last_message: :desc)

相关问题