0

すいません、タイトルをできるだけわかりやすく書こうとしたのですが意味不明になってしまいこれ以上うまく書けませんでした。

Phraseという自分自身をTranslationをいう名前のクラスがあり、そのクラスがhas_manyVoiceというクラスを持つのですが、特定のPhraseTranslationが存在し、そのVoiceが一つもない要素を取得したいのですがクエリがかけずに躓いています。

app/models/phrase.rb

class Phrase < ActiveRecord::Base
  has_many :translatabilities
  has_many :translations, through: :translatabilities
  has_many :voices
end

app/models/translatability.rb

class Translatability < ActiveRecord::Base
  belongs_to :phrase
  belongs_to :translation, :class_name => 'Phrase'
end

以下の様なクエリを試してみたのですが、これではTranslationとして取得したモデルのVoiceが一つもなくてもPhrase側のVoiceが存在すると取得対象外になってしまいます。

Phrase.includes(:translations).
    where.not(translatabilities: {phrase_id: nil}).
    includes(:voices).where(voices: {phrase_id: nil})

どのようにすれば「Translationsが存在し、そのどのTranslationVoice持たない」要素をとってこれるでしょうか?

Rubyの式で書くと

phrase.translations.present? && phrase.translations.all?{|t| t.voices.empty? }

が真になる要素を抜き出したいです。

2
  • テーブルがどのような状態の時にどのような結果になって欲しいのか、今はどうなるのかがわかりにくいです。「Phraseという自分自身をTranslationをいう名前のクラス」というのは意味不明です。
    – suzukis
    2016年1月3日 23:32
  • 中間テーブルのモデル内容を記述し忘れていたので追記しました。
    – ironsand
    2016年1月3日 23:52

1 件の回答 1

1

こういうケースは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のバージョンアップで動かなくなるケース(参考)も何度か見てきたので。

1
  • 詳しい解説ありがとうございます。はい、SQLの方がわかりやすい時はSQLを使おうと思っています。ただすいません、質問文が不明瞭でした。正しくは「Translationsが存在し、そのどのTranslationVoice持たない」でした。初めから書いておけばよかったのですがRubyの式でどのようなphraseが欲しいかを記述しておきました。
    – ironsand
    2016年1月4日 1:49

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。