Question

I am using Ruby on Rails and I have to create an importer from one database to another. There are over 100 tables in each database and I don't want to create a model for each table. Is there any possibility to create queries, specifying a table name? I don't want a model bind to a table.

For example: FirstDatabase.select('*').from('some_table').where(...)

Without set_table_name ... just dynamic models

Also I need to do inserts in different tables

Was it helpful?

Solution

I would not use models for that task at all. Instead, use the #select_all, #exec_insert, #exec_update, and #exec_delete methods of the base connection as appropriate.

ActiveRecord::Base.connection.select_all("select * from #{table_name}")

Returns an array of hashes for rows.

ActiveRecord::Base.connection.exec_insert("insert into #{table} (foo, bar) values(#{foo}, #{bar})

Inserts a row. The values will need to be properly escaped strings, dates, etc. for whatever database you are using.

ActiveRecord::Base.connection.quote("fo'o")
=> "'fo''o'"  # When server is PostgreSQL

Returns a quoted string representation suitable for use in a SQL statement.

now=Time.now
=> Fri Aug 23 02:24:40 -0700 2013

ActiveRecord::Base.connection.quote(now)
=> "'2013-08-23 09:24:40.365843'"

Returns a quoted date/time representation in UTC timezone.

To deal with the multiple databases, you can do something like set up a single model for each, and then get connections from those models instead of from 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("...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top