尝试在Rails 3.0.7中使用find_by_sql时,我遇到了一个非常奇怪的问题。 Rails不返回任何内容(空结果,[])但是如果我复制&将完全相同的查询粘贴到mysql中,它会返回一个结果。
这就是我在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 :(得分: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")
答案 1 :(得分: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
编辑:看起来我错了 - sanitize_sql将采用字符串,数组或散列。仍然...
我的提示:尝试在没有find_by_sql()
的情况下执行此操作