Search code examples
ruby-on-railsrubyassociations

Rails: Find users where the user id is stored in a associated table


I need to get a list of users from a associated table.

From, for example 35 users, i need just these users, like below in the screenshot.

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

How is the way to get the user records out of the applicants table?


Solution

  • Users that have applicants:

    User.joins(:applicants).all

    Bonus: Users that have no applicants:

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