我根本不会使用模型来完成这项任务。相反,请酌情使用基本连接的#select_all、#exec_insert、#exec_update 和#exec_delete 方法。
ActiveRecord::Base.connection.select_all("select * from #{table_name}")
返回行的哈希数组。
ActiveRecord::Base.connection.exec_insert("insert into #{table} (foo, bar) values(#{foo}, #{bar})
插入一行。对于您使用的任何数据库,这些值都需要正确转义字符串、日期等。
ActiveRecord::Base.connection.quote("fo'o")
=> "'fo''o'" # When server is PostgreSQL
返回适合在 SQL 语句中使用的带引号的字符串表示。
now=Time.now
=> Fri Aug 23 02:24:40 -0700 2013
ActiveRecord::Base.connection.quote(now)
=> "'2013-08-23 09:24:40.365843'"
以 UTC 时区返回带引号的日期/时间表示。
要处理多个数据库,您可以为每个数据库设置一个模型,然后从这些模型而不是 ActiveRecord::Base 获取连接。
class TableInDbA << ActiveRecord::Base
establish_connection "database_a_#{Rails.env}"
end
class TableInDbB << ActiveRecord::Base
establish_connection "database_b_#{Rails.env}"
end
TableInDbA.connection.select_all("...