Rails:如何找到没有关联记录的相同模型关联记录

Nac*_*cho 0 ruby-on-rails

鉴于:

class Account < ApplicationRecord
  belongs_to :super_account, class_name: 'Account', optional: true, foreign_key: 'account_id'
  has_many   :sub_accounts,  class_name: 'Account'
end
Run Code Online (Sandbox Code Playgroud)

查找没有 sub_accounts 的所有帐户的 rails 方法是什么?

max*_*max 6

Account.left_joins(:sub_accounts)
       .where(sub_accounts_accounts: { id: nil })
Run Code Online (Sandbox Code Playgroud)

sub_accounts_accounts 是连接表在查询中的别名:

SELECT "accounts".* FROM "accounts" 
LEFT OUTER JOIN "accounts" "sub_accounts_accounts" 
  ON "sub_accounts_accounts"."account_id" = "accounts"."id" 
WHERE "sub_accounts_accounts"."id" IS NULL LIMIT $1
Run Code Online (Sandbox Code Playgroud)

.left_joins(又名左外连接)是在 Rails 5 中引入的。在 Rails 4 中,您需要使用.joinssql string

Account.joins(%q{
  LEFT OUTER JOIN accounts sub_accounts
  ON sub_accounts.account_id = accounts.id
}).where(sub_accounts: { id: nil })
Run Code Online (Sandbox Code Playgroud)