Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I perform a INSERT-SELECT operation with the Rails API?

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)

like image 243
Daniel Rikowski Avatar asked Jan 22 '11 14:01

Daniel Rikowski


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ORM in Ruby on Rails?

Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.


1 Answers

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.

like image 150
karthiks Avatar answered Nov 15 '22 13:11

karthiks