Inserting multiple rows from array

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

David L. wrote:

contain:


|job_id |contact_id|

| 1 | 4 |

| 1 | 8 |

Any advice?

  1. Create an array of records, each a field array containing the job IDs
    and
    the respective contact IDs.

  2. Submit the array to the database in a way that the database
    understands.

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?

Paul L. wrote:

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.

David L. wrote:

contain:


|job_id |contact_id|

| 1 | 4 |

| 1 | 8 |

Any advice?

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.

contact_ids.map { |num|
AssignedJob.create({:job_id => job.id, :contact_id => num})
}

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Joey wrote:

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-----