Rails:查找用户ID存储在关联表中的用户

问题描述 投票:0回答:2

我需要从关联表中获取用户列表。

例如,从35个用户中,我只需要这些用户,如下面的屏幕快照。

enter image description here

class Book < ApplicationRecord
  has_many :applicants
  has_many :users, through: :applicants
end

class User < ApplicationRecord
  has_many :applicants
  has_many :books, through: :applicants
end

class Applicant < ApplicationRecord
  belongs_to :user
  belongs_to :book
end

如何从applicants表中获取用户记录?

ruby-on-rails ruby associations
2个回答
1
投票

您可能需要再澄清一点问题。您发布的屏幕截图是如何过滤表格的?是申请人的前11个ID吗?如果希望申请人中存在所有用户,则可以运行-User.join(:applicants).all

或者,如果只希望所有用户,则可以运行User.all


0
投票

有申请人的用户:

User.joins(:applicants).all

奖励:没有申请人的用户:

User.left_outer_joins(:applicants).where(applicants: { id: nil })

© www.soinside.com 2019 - 2024. All rights reserved.