Rails find_by_sql - 如何运行泛型查询

Vij*_*Dev 1 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]
Run Code Online (Sandbox Code Playgroud)

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

有没有其他方法来运行这样的通用查询?想知道使用find_by_sql的整个方法的变化是否也可以解决原始问题.

Phi*_*oss 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]))
Run Code Online (Sandbox Code Playgroud)

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