Copying Records

This might seem like a silly quesiton but it’s been baffling me all day!

I want to copy all records matching certain criteria from table A to
table B.

I know how to do his with SQL but not with RoR.

Well, you could still do it with SQL:

ActiveRecord::Base.connection.execute( )

(may want to check for actual method names and the like, buts its
available)

Hi John,

John H. wrote:

I want to copy all records matching certain criteria
from table A to table B.

I know how to do his with SQL but not with RoR.

I’m assuming you want to do this with RoR :wink:

If that’s the case, the simplest way is to do a .find(:all) and then
save
each record in the returned array. Base case looks something like…

records = A_singular_version_of_table_name.find(:all)
records.each |record|
#assign fields in A to fields in B
B_singular_version_of_table_name.field1 = record.field1
#etc.
B.save
end

hth,
Bill

Cheers Bill,

That worked a treat once I figured out to put in a ‘do’ before the
|record|

Many thanks

John

Oops. Sorry about that :wink:

Best regards,
Bill

If you have two different tables than you would have two different
classes (models) to work with. Let say that you have two classes
OldThing and NewThing. You want to copy all of the records from the
old_things table to the new_things table. You would do it like this:

old_things = OldThing.find(:all, :conditions => my_sql_where_clause)
old_things.each do |old_thing|
new_thing.create(old_thing.attributes)
end

This would go through each of the records in the old_things table and
add them to the new_things table assuming the field names matched up.

Bill W. wrote:

Hi John,

John H. wrote:

I want to copy all records matching certain criteria
from table A to table B.

I know how to do his with SQL but not with RoR.

I’m assuming you want to do this with RoR :wink:

If that’s the case, the simplest way is to do a .find(:all) and then
save
each record in the returned array. Base case looks something like…

records = A_singular_version_of_table_name.find(:all)
records.each |record|
#assign fields in A to fields in B
B_singular_version_of_table_name.field1 = record.field1
#etc.
B.save
end

hth,
Bill

Can someone give a working example of this code, i dont really
understand it. i just want to copy data from selected fields from table
A to table B just like in the code.