pkberlin
pkberlin

Reputation: 852

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?

Upvotes: 1

Views: 1092

Answers (2)

Rahul
Rahul

Reputation: 1505

You might need to clarify the question a bit more. The screenshot, you have posted, how did you filter your table? Is it the first 11 ids from applicants? If you want all users that are present in applicants, you can run - User.joins(:applicants).all

Or if you simply want all users, you can run User.all

Upvotes: 1

Yshmarov
Yshmarov

Reputation: 3729

Users that have applicants:

User.joins(:applicants).all

Bonus: Users that have no applicants:

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

Upvotes: 1

Related Questions