rails read the file and store the database -
saved .rb file in app/component/text.rb. want read , store database.
in file has 5 rows , table have 5 rows.i want save line line.you can understand question.i use mysql database.
please me....
thanks, kingston.s
i missed rails- , ruby-version, operating system use , clear problem description...anyway
assuming meant database have 5 fields , want read , write record file:
assuming file contain record model "apple "with fields id, title , description.
read new apple file:
indexes = [:id, :title, :desc].reverse # careful data saved reverse because pop takes last element first record_params = {} handle = file.open("apple.record","r") handle.lines.each |line| record_params[indexes.pop]=line.chomp #use chomp rid of trailing \n end handle.close apple.create!(record_params)
write apple id 7 file
indexes = [:id, :title, :desc] record = apple.find(7) to_save = indexes.map{|i| record.send i} handle = file.open("apple.record","w") handle.write(to_save.join("\n")) handle.close
beware escape linebreaks in data if there possible..
anyway easier use yaml:
#write first apple file handle = file.open("apple.record", "w") handle = apple.first.to_yaml handle.close #read file new record record_params = yaml.load file.read("apple.record") apple.create!(record_params)
all worked in rails 3, remember, saving id well, therefore saving , loading cause id change, because record given id existed.
Comments
Post a Comment