2011-06-17 96 views
0

當試圖在Rails 3.0.7中使用find_by_sql時,我有一個很奇怪的問題。 Rails不會返回任何東西(空結果,[]),但如果我複製&將完全相同的查詢粘貼到mysql中,它將返回結果。find_by_sql Ruby on Rails 3沒有結果

這就是我想用Rails:

Document.find_by_sql(["select d.* from documents d, categorizations cg, combinations co where d.id = cg.document_id and co.id = cg.combination_id and co.assigned_parent_category_id=?", 1) 

回報:[]

,這就是我在MySQL做:

select documents.* 
from documents, categorizations, combinations 
where documents.id = categorizations.document_id 
    and combinations.id = categorizations.combination_id 
    and combinations.assigned_parent_category_id=1 

回報:1分的結果

難道這是一個Rails錯誤還是我做錯了什麼?謝謝 !

回答

0

你有使用find_by_sql的原因嗎?

的文檔表明,提供一個數組(你的語法看起來錯反正 - 哪來的右方括號?)是不是一種選擇 - 你必須提供SQL

# File activerecord/lib/active_record/base.rb, line 472 
def find_by_sql(sql) 
    connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) } 
end 

編輯:看起來像我m錯誤 - sanitize_sql將採用字符串,數組或散列。還是......

我的提示:儘量要做到這一點不用的find_by_sql()

2

變化

Document.find_by_sql(["select d.* from documents d, categorizations cg, 
      combinations co where d.id = cg.document_id and co.id = cg.combination_id 
      and co.assigned_parent_category_id=?", 1) 

Document.find_by_sql(["select d.* from documents d, categorizations cg, 
      combinations co where d.id = cg.document_id and co.id = cg.combination_id 
      and co.assigned_parent_category_id=?", 1]) 

OR

Document.find_by_sql("select d.* from documents d, categorizations cg, 
      combinations co where d.id = cg.document_id and co.id = cg.combination_id 
      and co.assigned_parent_category_id=1")