10

I have to duplicate a BLOB field from one table into another and I want to use a INSERT-SELECT query to achive this.

INSERT INTO target_table (key, data, comment)
    SELECT 'my key', data, 'some comment' FROM source_table

Can this be done with the Rails API?

Of course I could always use ActiveRecord::Base.connection to send a native query to the database, but I'm hoping to find a "Rails way" to do this. (One which doesn't involve actually loading the data in my Rails application)

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
  • For those of us not as savvy at navigating Rails documentation, would it not make sense to have an example of the ActiveRecord::Base.connection API call here? I'm finding this non-obvious to ferret out of the docs.... – Philip Jan 13 '16 at 01:34

1 Answers1

4

This is a typical scenario where using the SQL directly using ActiveRecord::Base.connection makes sense and sensibility. There can't possibly be any rails way to it as you described. Even if there were to be one, it has to load it in memory and insert it into the target table involving two models; this is insanity.

karthiks
  • 7,049
  • 7
  • 47
  • 62
  • 5
    I tend to agree with the "typical scenario" statement, but why do you think there can't possibly be any way? Just consider what amazing stuff Arel can do without loading everything into memory. – Daniel Rikowski Feb 02 '11 at 19:57
  • Thanks DR, it is from your comment above I happened to learn about Arel with Rails-3. Hence I vote it up! With Arel, a query like the one in question is probably possible. – karthiks Feb 03 '11 at 14:36
  • it's 2022, still no rails way to do this? – Afsan Abdulali Gujarati Jun 11 '22 at 20:56