views:

27

answers:

2

I want to copy all the rows from my table with single column update.

Example.

Table County has 1000 rows and i want to copy all the rows with single column update.

What is the proper way to do that ?

A: 

Assuming I understand you correctly, I'd do something like

INSERT INTO NewTable (Col1, Col2, Col3)
SELECT Col1, Col2, UpdateFunction(Col3)
FROM County

Where Col3 is the column you want to update, and UpdateFunction is the function you wish to use to update the column.

EDIT: Of course this is SQL, not Rails - I didn't look close enough at the question's tags :-)

SamStephens
@Sam I want the same thing but with rails way.
krunal shah
+1  A: 

This question describes how to use clone to copy your record.

Assuming the 1000 records are already in an Enumerable called counties, we end up with

counties.each { |county|  
    county_copy = county.clone
    county_copy.col3 = update_function(county_copy.col3)
    county_copy.save
}
SamStephens
@Sam I have already applied this method in my code. But with this code it will create 1000 queries. Can't we insert all this record with single query ?
krunal shah
Not natively. I'd suggest using the SQL I posted below if this is a one off. And if this is something you need to do on a regular basis, you may need to rethink your data structure. However I did see this blog post which may provide pointers: http://rubypond.com/blog/bulk-insertion-of-data-with-activerecord
SamStephens
@SamStephens I have used ar-extension to solve out my problem.
krunal shah