2017-02-06 5 views
0

実行時に正しく動作するこのSQLクエリがありますが、それをどのように表現してActiveRecord経由で同じデータを取得するのですか?SQLクエリを最適化されたRails Active Recordクエリに変換するには?

select concat(o.code, ' - ', u.name) 
from users u join user_organizations uo on u.id = uo.user_id 
join organizations o on uo.organization_id = o.id 
where u.approved = true 
    and u.deleted_at is null 
    and o.deleted_at is null 
    and u.type = 'Banker' 
order by o.code asc; 

私はこの

Banker.joins(:user_organizations => :organization) 
    .where(:approved => true) 
    .select("concat(organizations.code, users.name)") 
    .order("organizations.code asc") 

を試みたが、それは動作しませんでしたし、私はそれが動作するように期待していました。

+0

あなたは結果が期待されますか?あなたのモデルBankerはおそらく 'concat(organizations.code、users.name) '属性を持たないでしょう – Fallenhero

+0

生成されたSQL –

答えて

2

あり、それは難しいあなたの関係はBankerOrganization間に設定されているどのように適切に

  • に答えるために作るの質問に対処し、オープンする物事のカップル?
  • 質問:あなたは何を期待していますか?
  • このソフト削除機能(deleted_at is NULL)にいくつかの宝石を使用していますか? (例:paranoia
  • あなたのバージョンから生成されたSQLクエリを提供できますか?私はあなたがのために上記の妄想の宝石を使用している場合は、次の

    User.select("concat(organizations.code, ' - ', users.name)") 
        .includes(:organizations) 
        .where('users.deleted_at is not null') 
        .where('organizations.deleted_at is not null') 
        .where('users.type = ?', 'Banker') 
        .order('organizations.code ASC') 
    

    を行うことができるはずもしそうなら、あなたのセットアップは、この

    class User < ApplicationRecord 
        has_and_belongs_to_many :organizations 
    end 
    
    class Organization < ApplicationRecord 
        has_and_belongs_to_many :users 
    end 
    

    ようSTHに見えることを前提としてい

ユーザーと組織の*.deleted_at is not nullクエリ部分が自動的に追加され、rubyクエリがこのようにsthに減少します。

User.select("concat(organizations.code, ' - ', users.name)") 
    .includes(:organizations) 
    .where('users.type = ?', 'Banker') 
    .order('organizations.code ASC') 

まれに、レールガイドについてはわかりません。 article about associationsへのリンクは次のとおりです。