1

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

2
  • Do you need to use rails? Might be easier from outside Commented Aug 23, 2013 at 8:06
  • We use rails because of multithreading Commented Aug 23, 2013 at 8:09

1 Answer 1

4

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("...
Sign up to request clarification or add additional context in comments.

1 Comment

You rock, this is awesome! I didn't know that I could do this. Note that for longer, more complex SQL strings, including UNION statements, you can build the multi-line string using %Q().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.