2011-04-06 130 views
1

下面,lo屬於titres,titre有很多個lo。connection.select_all vs select with with rails in rails 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;") 

它檢索。

有什麼fondamental我在這裏失蹤?

還是選擇限制從數據庫表中檢索字段,還是從連接表中沒有任何內容?

是否有一個更好的方式來執行此查詢,以便它提供與connection.select_all版本相同的結果?

環境:軌道3.0.5與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)