2011-04-06 7 views
1

ここではloは力価に属し、titreにはloが多くあります。connection.select_allとレールで結合を選択3

私が使用:

LO.select(["los.id","date_ord","soc","pv"]).joins(:titre). 
     where(['year(date_ord) = ? and pv is not null',"#{date_ord}"]). 
     group("num_ordre").order("soc,date_ord") 

それは力価からフィールドのSOCを取得しません。

私が使用している場合のに対し:

search_year = "year(date_ord) = '#{date_ord}'" 
connection.select_all("select los.id, date_ord, soc, pv " + 
    "from los inner join titres on los.titre_id=titres.id " + 
    "where #{search_year} and pv is not null " + 
    "group by num_ordre order by soc, date_ord;") 

それを取得しません。

ここに何か不足していますか?

または、選択すると、fromデータベーステーブルのフィールドの検索に制限があり、結合テーブルからの検索は制限されますか?

このクエリを実行して、connection.select_allバージョンと同じ結果が得られるようにする方法はありますか?

環境:レール3.0.5 with jruby 1.6(ルビー1.8.7)。

ありがとうございました。

答えて

0

アクティブレコードファインダーメソッドは、それらを呼び出すモデルに添付されています。したがって、彼らは結果がモデルフォーマットに従うことを期待し、このモデルのオブジェクトを構築します。

一方、connection.select_allはモデルに依存せず、単純にハッシュの配列を返します。

0

あなたは、モデルが作成さを避けるためにActiveRecord::Base.connection.select_allにあなたの作成したクエリを渡すことができますし、まだあなたがそれを生のSQL文字列渡されたかのような結果が返されています:

query = LO.select(["los.id","date_ord","soc","pv"]).joins(:titre). 
     where(['year(date_ord) = ? and pv is not null',"#{date_ord}"]). 
     group("num_ordre").order("soc,date_ord") 

data = ActiveRecord::Base.connection.select_all(query) 
関連する問題