テーブルを複数joinしたい
現在Arelを使った外部結合の処理を考えています。
テーブルNote の user_id と テーブルUser の idで外部結合したいのと、
テーブルNote の child要素 を alias して取得した child_note の user_id と テーブルUser の id で外部結合し、
両者(親要素・子要素のUserテーブル)からnameを取得したいと考えています。
以下、コードです。
ruby
1note = Note.arel_table 2user = User.arel_table 3child_note = Note.arel_table.alias('child') 4join_table = note.join(child_note, Arel::Nodes::OuterJoin). 5 on(note[:id].eq(child_note[:parent_id])) 6 .join(user, Arel::Nodes::OuterJoin). 7 on(note[:user_id].eq(user[:id])) 8 .join(user, Arel::Nodes::OuterJoin). 9 on(child_note[:user_id].eq(user[:id])).join_sources 10 11@note = Note.joins(join_table).where('note.note_id = ? AND note.parent_id IS NULL AND note.user_id != ?', @note.id, @note.user_id).select(user[:name].as('parent_name'), user[:name].as('child_name'))
上記のコードはSQLite3::SQLException: ambiguous column name
となります。
userテーブル名がparentとchildで被ってしまっていることが原因だと思います。
困っている点としては明示的に note(親)でuserテーブルjoinした結果を「user_parent」と命名し、child_note(子)でuserテーブルとjoinした結果を「user_child」と命名し、
両者のnoteのnameを一意に取得できるようにしたいです。
試行錯誤してみたものの、別名で命名し、取得することができていません。
小さなアドバイスでも良いので、ご回答頂ければと思います。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。