【问题标题】:Rails find_by_sql - how to run generic queriesRails find_by_sql - 如何运行通用查询
【发布时间】:2009-12-20 14:38:33
【问题描述】:

我需要执行这个查询来找出 MySQL 将用于特定表的下一个 auto_increment 值。

find_by_sql ["select auto_increment from information_schema.tables where   
table_schema = ? and table_name = ? and auto_increment is not null", db_name, tbl_name]

如何调用这个特定的查询?这适用于我调用它并返回包含模型对象的大小为 1 的数组的任何模型。编辑:该对象包含一个名为 attributes 的散列,其中包含所需的 auto_increment 值。

还有其他方法可以运行此类通用查询吗?想知道改变使用 find_by_sql 的整个方法是否也可以解决原来的问题。

【问题讨论】:

    标签: sql ruby-on-rails finder-sql


    【解决方案1】:

    如果您想在不涉及模型的情况下运行原始 SQL,可以直接获取connection 并调用select_* 方法之一(在本例中为select_value)。这些方法只是将 SQL 语句作为字符串,因此您可以调用sanitize_sql_array 来转换您的参数数组(注意sanitize_sql_array 是受保护的,因此可能需要send

    ActiveRecord::Base.connection.select_value(
      ActiveRecord::Base.send(:sanitize_sql_array, 
       ["select auto_increment from information_schema.tables where
        table_schema = ? and table_name = ? and auto_increment is not null", 
        db_name, tbl_name]))
    

    返回的结果将是一个字符串。

    【讨论】:

      【解决方案2】:

      所以包含模型的一个对象的数组实际上是 ActiveRecord 试图将查询结果转换为对象。

      查看该对象的#columns [edit: err "attributes"] 属性并查看 ActiveRecord 将您要查找的结果放在哪里(我怀疑它会在名为 auto_increment 的列下)

      【讨论】:

      • @Ryan:正确。我知道从查询中获取必要输出的方法。我要问的是在特定模型上调用此查询的整个方法是否正确,以及是否有任何其他方法可以调用该方法。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      相关资源
      最近更新 更多