こういうケースはSQLで書いてしまうのが手っ取り早いと思います。
class Phrase < ActiveRecord::Base
has_many :translatabilities
has_many :translations, through: :translatabilities, class_name: 'Phrase'
has_many :voices
# 特定のPhraseのTranslationが存在し、そのVoiceが一つもない要素を取得したい
scope :with_translation_without_voice, -> {
query = <<-SQL
EXISTS (
SELECT *
FROM translatabilities ta
INNER JOIN phrases t
ON t.id = ta.translation_id
WHERE
ta.phrase_id = phrases.id
AND NOT EXISTS (
SELECT *
FROM voices v
WHERE
v.phrase_id = t.id
)
)
SQL
where(query)
}
end
以下はテストコードです。
require 'test_helper'
class PhraseTest < ActiveSupport::TestCase
test '特定のPhraseのTranslationが存在し、そのVoiceが一つもない要素を取得したい' do
translation_with_voice = Phrase.create! name: '翻訳、Voiceあり'
translation_with_voice.voices.create! name: '音声1'
translation_without_voice = Phrase.create! name: '翻訳、Voiceなし'
phrase_with_translation_and_voice = Phrase.create! name: 'フレーズ、音声付きの翻訳あり'
Translatability.create! phrase: phrase_with_translation_and_voice, translation: translation_with_voice
phrase_with_translation_without_voice = Phrase.create! name: 'フレーズ、音声なしの翻訳あり'
Translatability.create! phrase: phrase_with_translation_without_voice, translation: translation_without_voice
phrase_without_translation = Phrase.create! name: 'フレーズ、翻訳なし'
phrases_by_ruby = Phrase.all.select {|phrase| phrase.translations.present? && phrase.translations.all?{|t| t.voices.empty? } }
assert_equal [phrase_with_translation_without_voice].map(&:name), phrases_by_ruby.map(&:name)
phrases_by_scope = Phrase.with_translation_without_voice
assert_equal [phrase_with_translation_without_voice].map(&:name), phrases_by_scope.map(&:name)
end
end
schema.rbは以下のようになっています。
ActiveRecord::Schema.define(version: 20160104001330) do
create_table "phrases", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "translatabilities", force: :cascade do |t|
t.integer "phrase_id"
t.integer "translation_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "translatabilities", ["phrase_id"], name: "index_translatabilities_on_phrase_id"
add_index "translatabilities", ["translation_id"], name: "index_translatabilities_on_translation_id"
create_table "voices", force: :cascade do |t|
t.string "name"
t.integer "phrase_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "voices", ["phrase_id"], name: "index_voices_on_phrase_id"
end
コードはGitHubにもアップしています。
https://github.com/JunichiIto/not-exists-sandbox
ちなみに「生SQLは絶対に書きたくない、Arelを駆使してなんとしてでも生SQLを避ける!」と考える人もときどき見かけますが、僕は「そんなに無理せずSQL書けばいいやん」と考える人です。
Arelを駆使したコードは非常に読みづらいですし、Railsのバージョンアップで動かなくなるケース(参考)も何度か見てきたので。