Rails 活动记录查询 - 显示项目到项目 creators/members

Rails Active Record Query - display projects to project creators/members

我有三个 table:User 通过设计、ProjectProjectUser

一个 User 可以是许多 ProjectProjectUser 的 table 的一部分。我如何查询才能使 Project 的索引操作显示当前用户已创建并且是其成员的项目?

假设我有三个项目和两个团队成员:

当我登录时:


这是我的模型、控制器和模式:

projects_controller.rb

@projects = current_user.projects.joins(:project_users).distinct.order("created_at DESC")

project.rb

class Project < ApplicationRecord
  has_many :project_users
  has_many :users, through: :project_users
end

user.rb

class User < ApplicationRecord
  has_many :project_users
  has_many :projects, through: :project_users
end

project_user.rb

class ProjectUser < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

schema.rb

create_table "project_users", force: :cascade do |t|
    t.bigint "user_id", null: false
    t.bigint "project_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["project_id"], name: "index_project_users_on_project_id"
    t.index ["user_id"], name: "index_project_users_on_user_id"
end

我认为这对你有用

@projects = current_user.projects.distinct.order("created_at DESC")

您不需要:joins(:project_users)

For more info about the has_many :through Association: https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

这是适用于我的案例的查询

Project.joins(:project_users).where(project_users: {user_id: current_user.id}