Rails find_by_sql - 如何运行泛型查询

时间:2009-12-20 14:38:33

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

我需要执行此查询以找出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的整个方法的变化是否也可以解决原始问题。

2 个答案:

答案 0 :(得分:6)

如果要在不涉及模型的情况下运行原始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]))

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

答案 1 :(得分:0)

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

查看该对象的#columns [edit:err“attributes”]属性,看看ActiveRecord放置了您正在查找的结果的位置(我怀疑它将位于名为auto_increment的列下)

相关问题