-1
i saved .rb file in app/component/text.rb. i want to read and store the database.
在该文件中有5行,我的桌子也有5个rows.i要保存一行line.you能理解我的question.i使用MySQL数据库。轨读取该文件,并存储在数据库
please help me....
感谢, kingston.s
i saved .rb file in app/component/text.rb. i want to read and store the database.
在该文件中有5行,我的桌子也有5个rows.i要保存一行line.you能理解我的question.i使用MySQL数据库。轨读取该文件,并存储在数据库
please help me....
感谢, kingston.s
我错过了rails-和红宝石版本,您使用的操作系统和明确的问题描述...反正
假设你的意思是你的数据库将有5个字段,并且您想要读取和写入文件的记录:
假设该文件将包含字段id,标题和说明的模型“Apple”的记录。
从文件中读取新的苹果:
indexes = [:id, :title, :desc].reverse # be careful the data will be saved reverse because pop takes the last element first
record_params = {}
handle = File.open("Apple.record","r")
handle.lines.each do |line|
record_params[indexes.pop]=line.chomp #use chomp to get rid of the trailing \n
end
handle.close
Apple.create!(record_params)
写苹果ID 7到文件
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
当心逃跑的换行符在你的数据是否有任何可能..
无论如何,使用YAML会容易得多:
#write the first apple to the file
handle = File.open("Apple.record", "w")
handle = Apple.first.to_yaml
handle.close
#read the file to a new record
record_params = YAML.load File.read("Apple.record")
Apple.create!(record_params)
所有这些工作在Rails 3中,但请记住,您也保存了id,因此保存和加载将导致id发生更改,因为具有给定id的记录已存在。
我知道语言可能是这里的障碍,但也许你可以在解释你的问题时做得更好。现在这个问题是不可能回答的。 – Obie 2011-02-24 05:28:49