2017-01-09 8 views
2

組織モデルに属するエントリモデルが2回あります。pluckを使用してclass_nameに関連付けられたモデルから属性を取得する方法

class Entry < ActiveRecord::Base 
    belongs_to :organization 
    belongs_to :temp_organization, class_name: "Organization" 
end 

私はpluckを使用して、関連団体とtemp_organization名をオフに引っ張る単一のARクエリを記述しようとしています。

Entry 
    .includes(:organization, :temp_organization) 
    .pluck('organizations.name', 'temp_organizations.name') 

これは、次のエラーでクラッシュ:

理にかなっている
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "temp_organizations" 

は - その協会が定期的organizationsテーブルを介して管理されているので、何もtemp_organizationsテーブルがありません。

pluckにtemp_organization名をプルするにはどうすればよいですか?

答えて

1

、使用してみてください複数が同じテーブルに合流するとので、ARは、いくつかの魔法を行い、あなたは右のテーブル名をプルアップすることができない理由である、テーブルの名前を変更します。

Entry.includes(:organization, :temp_organization).to_sql 

次のようなものを取得する必要があります:私は、テーブル名を疑うだろう

...INNER JOIN \"organizations\" \"entries_temp_organizations\" ON \"entries_temp_organizations\"... 

は「entries_temp_organizations」(ある

あなたは、テーブル名が生成されるSQLを見て、何であるか確認することができます結合表のアルファベット順のAR規則に従って)。正しいテーブル名を使用すると、そのトリックが実行されます。

+0

'Entry .... to_sql'を実行すると、3つのDBクエリ、SELECT \" entries \ "。* FROM \" entries "\" "、" SELECT "組織をトリガします。* FROM" organizations "WHERE "組織"、 "組織"、 "組織"、 "組織"、 "組織"、 "組織"、 "組織"、 "組織" '、私はあなたが期待しているもののように見える単一のSELECT文を取得しますが、テーブル名は' temp_organizations_entries'になりますが、インクルードまたはジョインを使用しても同じエラーが発生します。 – CodeSmith

+0

どこかで自分のコードに誤りがあったに違いない。私は 'temp_organizations_entries.name'を使用してすべてが今働いています。ありがとうございました。 – CodeSmith

1

Entry 
    .includes(:organization, :temp_organization) 
    .references(:organization, :temp_organization) 
    .pluck('organizations.name', 'entries_temp_organizations.name') 
+0

いいえ、私はまだ同じエラーが発生します(テーブル名が 'temp_organizations_entries'に変更されます)。 – CodeSmith

+0

@CodeSmith 'Entry'モデルのテーブルの名前は何ですか? –

+0

@ CodeSmithまた、 'organization'モデルのテーブル名は何ですか? –

関連する問題