我需要从关联表中获取用户列表。
例如,从35个用户中,我只需要这些用户,如下面的屏幕快照。
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
表中获取用户记录?
您可能需要再澄清一点问题。您发布的屏幕截图是如何过滤表格的?是申请人的前11个ID吗?如果希望申请人中存在所有用户,则可以运行-User.join(:applicants).all
或者,如果只希望所有用户,则可以运行User.all
有申请人的用户:
User.joins(:applicants).all
奖励:没有申请人的用户:
User.left_outer_joins(:applicants).where(applicants: { id: nil })