Brainmaniac
Brainmaniac

Reputation: 2556

Persist hash to corresponding db-table

I have a hash:

my_hash = {
  blue: 2,
  red: 3,
  purple: 4,
}

I have a Model with corresponding db-table:

 ____________________
| id | color | count |
----------------------
|    |       |       |
----------------------

I want to put my hash in the table like this:

 ____________________
| id | color | count |
----------------------
|  1 | blue  |   2   |
|  2 | red   |   3   |
|  3 | purple|   4   |
----------------------

So my question is, How can I write code that persists the hash to the corresponding db-table?

Upvotes: 0

Views: 30

Answers (1)

ray
ray

Reputation: 5552

This can easily be done as below,

my_hash.each { |k,v| Model.create(color: k, count: v) }

Upvotes: 2

Related Questions