我有几个哈希存储在内存中的数组中,例如:
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数据库中?
答案 0 :(得分: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