【问题标题】:find_by_sql Ruby on Rails 3 no resultsfind_by_sql Ruby on Rails 3 没有结果
【发布时间】:2011-06-17 03:39:16
【问题描述】:

在尝试将 find_by_sql 与 Rails 3.0.7 一起使用时,我遇到了一个非常奇怪的问题。 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 错误还是我做错了什么?谢谢!

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案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)
    

    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")
    

    【讨论】:

      【解决方案2】:

      您使用 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() 的情况下执行此操作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-24
        • 1970-01-01
        • 1970-01-01
        • 2016-02-01
        • 2011-01-23
        • 2013-12-23
        • 2015-08-13
        • 2012-08-22
        相关资源
        最近更新 更多