[英]Rails find_by_sql - how to run generic queries
我需要執行此查詢以查找下一個將由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的數組來調用它的任何模型。 編輯:對象包含一個名為屬性的哈希,該哈希包含所需的auto_increment值。
還有其他方法可以運行此類通用查詢嗎? 想知道是否可以改變使用find_by_sql的整個方法來解決原始問題。
如果要在不涉及模型的情況下運行原始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]))
返回的結果將是一個字符串。
因此,包含模型的一個對象的數組實際上是ActiveRecord,試圖將查詢結果轉換為一個對象。
看一下該對象的#columns [edit:err“ attributes”]屬性,並查看ActiveRecord將您要查找的結果放在何處(我懷疑它會在名為auto_increment的列下)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.