我有一个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.然后,我将两者合并为活动记录关联.

这很管用,但我觉得这不是一个好办法.有谁知道做这件事更有效的方法吗?

推荐答案

您可以像这样连接申请者和项目表,并判断当前用户是申请者还是项目"所有者"

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

Ruby-on-rails相关问答推荐

仅当未在带有ENV[';Dyno';]的Heroku问题上运行时才初始化Sidekiq Cron

Rails 7.1.3如何在生产环境中查看堆栈跟踪

Heroku、Selenium、Chome和Chromedriver的复杂问题(抱歉,无法简单描述,请阅读详细信息)

如何不需要rails/all?

如何在 Arel 中重用单个绑定变量?

如何获取 Rails 表单构建器将为某个字段生成的 HTML名称属性?

2个空格或1个制表符,Rails社区的缩进标准是什么?

使用 Rspec 测试 Rails 3.1 可安装引擎

如何在 rails 中指定和验证枚举?

rails 模型 has_many 本身

是否可以在 Rails 集成测试或规范中指定用户代理?

ActiveRecord 查找现有表索引

在rails中带有内部文本或html的link_to image_tag

使用 PostgreSQL 的模式和 Rails 创建多租户应用程序

Rails 3 返回 HTTP 406 Not Acceptable?

Dotenv 多行变量

在 Rails 中,在特定时区创建特定时间(不是现在)的最佳方式是什么?

扩展 Devise SessionsController 以使用 JSON 进行身份验证

ArgumentError:ApplicationController 的副本已从模块树中删除,但仍处于活动状态

是否可以输出rake db:migrate产生的 SQL 更改脚本?