Rails:查找用户id存储在关联table中的用户
Rails: Find users where the user id is stored in a associated table
我需要从关联的 table 中获取用户列表。
例如 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
table中获取用户记录?
您可能需要进一步澄清问题。您发布的屏幕截图,您是如何过滤 table 的?它是申请人的前11个ID吗?如果你想要申请者中存在的所有用户,你可以 运行 - User.joins(:applicants).all
或者如果您只是想要所有用户,您可以 运行 User.all
有申请人的用户:
User.joins(:applicants).all
奖励:没有申请人的用户:
User.left_outer_joins(:applicants).where(applicants: { id: nil })
我需要从关联的 table 中获取用户列表。
例如 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
table中获取用户记录?
您可能需要进一步澄清问题。您发布的屏幕截图,您是如何过滤 table 的?它是申请人的前11个ID吗?如果你想要申请者中存在的所有用户,你可以 运行 - User.joins(:applicants).all
或者如果您只是想要所有用户,您可以 运行 User.all
有申请人的用户:
User.joins(:applicants).all
奖励:没有申请人的用户:
User.left_outer_joins(:applicants).where(applicants: { id: nil })