2011-12-09 59 views
0
存儲在內存中的數組,像

我有幾個哈希:如何將散列放入sqlite3數據庫?

ruby-1.9.3-p0 :020 > grok.tracks[0] 
=> {:track_id=>1391, :name=>"Becoming a Better Developer", :artist=>"Ruby Rogues", :album=>"Ruby Rogues", :genre=>"Podcast", :kind=>"MPEG audio file", :size=>110164706, :total_time=>4596271, :year=>2011, :date_modified=>"2011-08-29T04:49:04", :date_added=>"2011-08-29T04:49:04", :bit_rate=>192, :sample_rate=>44100, :release_date=>"2011-08-25T17:25:43", :persistent_id=>"6E564B7750B54D85", :track_type=>"File", :podcast=>true, :unplayed=>true, :location=>"file://localhost/Users/lunks/Music/iTunes/iTunes%20Media/Podcasts/Ruby%20Rogues/Becoming%20a%20Better%20Developer.mp3", :file_folder_count=>4, :library_folder_count=>1} 
ruby-1.9.3-p0 :021 > grok.tracks.size 
=> 14152 

我想將它們保存sqlite3的數據庫。我的數據庫已經有表格和我需要的所有列。數據庫名稱爲Library.sqlite3,表格爲tracks。 如何將所有哈希值放入Sqlite3數據庫中?

回答

3
require 'active_record' 

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite", 
    :database => "path/to/Library.sqlite3" 
) 

class Track < ActiveRecord::Base 
end 

# read hashes from wherever you have them 
# grok = Grok.read_tracks 

for track_hash in grok.tracks 
    track = Track.new(track_hash) 
    track.save 
end