简体   繁体   中英

how to insert hash into mysql using ruby

Let's say I have a hash:

{"MemberId"=>"MID-0000001", "MemberName"=>"Bruce", "OrderNumber"=>"ON-000000001"}

How can I insert this hash into orders tables of the db database in mysql?

Actually, this code will be a part of a scheduled task (of the Ruby on Rails app) to be running with whenever gem.

Let me know if I have to submit additional information.

Table orders has the same column names as in the hash.

Short answer: Active Record, or an alternative "object relational model".

Think of your tables as a schema'd serialization of your hash or object. Ruby, via Active Record, can be pretty intelligent about the de/serialization process, but it typically is defined by the reverse process - by reading your database, Active Record figures out what your data become when de-serialized, and from that, what happens when you serialize it.

So your usual use case would be to figure out what fields you want based on your objects (say, objects.each_with_object({}){|hash, obj| hash.merge!(obj)} and find all your fields), and then write up the Active Record declarations to make that happen. Then Model.create(obj) and you've just saved it to the database

But you're going "backwards", and so may be interested in some interesting features:

Serialization will let you store a pretty arbitrary object into a single field your database (inter-object references may be difficult), effectively mixing shema'd and schema-less paradigms. Postgres has a number of new features some of which are now part of rails 4 via ActiveRecord that will make it easy to do what you want - but both of those options work on a subset of your data. To just dump the whole thing, you can go schemaless and just not worry about it (instead, worry about other things!). Or graph , for completeness, but that doesn't sound like what you're looking for.

TL;DR:

1) Your hashes each describe an object, where each key is a column and each value a row - just define the Active Record model and read in your hash.

2) Stick a subset of the hash into a text column, and parse it out using active record serialization or advanced postgres features.

3) Go with a schema-less database and just stick the whole thing in there as-is.

In the end, your use case is the same: Model.create({"MemberId"=>"MID-0000001", ...})

@order = Order.new
@order.member_id = hash['member_id']
|
|
|
|
@order.save

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM