Inserting multiple rows from array

D

David Lelong

Hi,

I have two sets of values:

job.id = 1 and contact_ids = [4, 8]

I want to be able to iterate over all of values in the contact_id array
and create database records consisting of a job_id and contact_id.

So, in this example, the end result would be two new records that
contain:

--------------------
|job_id |contact_id|
--------------------
| 1 | 4 |
--------------------
| 1 | 8 |
--------------------

Any advice?

Thanks,

David
 
D

David Lelong

Paul said:
Did you want specific Ruby code to accomplish this? If so, just say so.

record_array = []

job_id = 1

contact_id.each |id| do
record_array << [ job_id, id ]
end

In order to take the next step, we'll need more information, like, what
database?

A little more code would be helpful. The database is MySQL and the
table is Assignedjobs.
 
J

J. B. Rainsberger

David said:
Hi,

I have two sets of values:

job.id = 1 and contact_ids = [4, 8]

I want to be able to iterate over all of values in the contact_id array
and create database records consisting of a job_id and contact_id.

So, in this example, the end result would be two new records that
contain:

contact_ids.map { |each|
AssignedJob.new({:job_id => job.id, :contact_id => each})
}.each { |each|
each.save!
}

This is ActiveRecord code, or pretty close to it. First, turn the data
into row objects, then ask each one to save itself.

I hope that helps.
 
Z

zdennis

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
contact_ids.map { |num|
AssignedJob.create({:job_id => job.id, :contact_id => num})
}

ActiveRecord::Extensions (for MySQL) handles bulk inserts using
multi-value insert statements. It goes up to 40x faster then current
ActiveRecord behavior.

API looks like:
MyModel.import( columns, array_of_value_sets, options_hash )

Documentation on it can be found here:
http://www.continuousthinking.com/are/import

Here are some MySQL benchmarks for current ActiveRecord#create vs.
ActiveRecord::Extensions#import comparing MyISAM to InnoDb to Memory tables:
http://www.continuousthinking.com/are/import-benchmarks-for-mysql

You can download the latest version from:
http://rubyforge.org/projects/arext/

What db adapter do you use? I am currently adding PostgreSQL support
over this holiday weekend.

Zach



-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFZnBtMyx0fW1d8G0RAkmxAJ403MJLT6jPjjuawRNBNDVH+y9JNgCfVb+j
cj0Kxm8B6zkLGZgIOOreMIw=
=kdbQ
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top