我有以下的數據庫架構和模型,構成了自我指涉的關聯,其中一個Phrase
具有其他Phrase
S的許多翻譯,通過Translation
協會:Rails的自我指涉協會加盟條件
模式:
ActiveRecord::Schema.define(version: 20151003213732) do
enable_extension "plpgsql"
create_table "phrases", force: :cascade do |t|
t.integer "language"
t.string "text"
end
create_table "translations", force: :cascade do |t|
t.integer "source_id"
t.integer "destination_id"
end
end
短語:
class Phrase < ActiveRecord::Base
has_many :translations,
class_name: "Translation",
foreign_key: "source_id"
has_many :destination_phrases,
through: :translations
has_many :inverse_translations,
class_name: "Translation",
foreign_key: "destination_id"
has_many :source_phrases,
through: :inverse_translations
enum language: [:eng, :spa, ...]
end
翻譯:
class Translation < ActiveRecord::Base
belongs_to :source_phrase,
class_name: "Phrase",
foreign_key: "source_id"
belongs_to :destination_phrase,
class_name: "Phrase",
foreign_key: "destination_id"
end
現在,我想基於源語言和目的地語言運行查詢。例如,我想查找英文短語及其各自的西班牙語翻譯。目前,我正在根據來源查詢短語,但之後我必須使用目標語言的select
方法過濾出結果。我有如下所示:
@translations = Translation.includes(:source_phrase, :destination_phrase)
.where(phrases: {language: @source_language})
# Select only destination phrases where the language matches
@translations = @translations.select {
|t| t.destination_phrase.language == @destination_language
}
我想消除select
調用,因爲這絕對應該在ActiveRecord的可能。 select
將被替換爲模型的where
查詢中的其他參數,但我無法弄清楚如何指定它。
它應該是這個樣子:
@translations =
Translation.includes(:source_phrase, :destination_phrase)
.where([source_phrase: {language: @source_language},
destination_phrase: {language: @destination_language}])
然而,ActiveRecord的認爲(理所當然),該where
子句中source_phrase
和destination_phrase
是表名。所以表名仍然是phrases
,但是當我不能指定的連接條件時,兩個連接,只是第一個。
如何在自我參照關聯上指定兩個單獨的聯接條件,它們都訪問同一模型上的相同屬性(Phrase
模型上的language
)?
是否可以查詢短語而不是翻譯? (短語:「目的地短語」:{語言:「西班牙語」}})' –
@LannyBose的確我可以查詢短語模型,但不幸的是不是那種我正在尋找的反應 - 我最終需要的模型是一個「翻譯」。在玩了大約兩個小時後,並使用類似於您所建議的「加入」代碼的東西后,我終於提出瞭解決方案。這也表明我的'短語'模型關聯不正確(不奇怪)。我自我回答,如果你想看看! –