开发者

rails read the file and store the database

开发者 https://www.devze.com 2023-02-12 21:21 出处:网络
i saved.rb file in app/component/text.rb. i want to read and store the database. in that f开发者_如何学JAVAile has 5 rows and my table also have 5 rows.i want to save line by line.you can understand
       i saved  .rb file in app/component/text.rb. i want to read and store the database.

in that f开发者_如何学JAVAile has 5 rows and my table also have 5 rows.i want to save line by line.you can understand my question.i use mysql database.

  please help me....

thanks, kingston.s


I missed the rails- and ruby-version, the operating system you use and a clear problem description...anyway

Assuming that you meant your database would have 5 fields and you want to read and write a record to a file:

Assuming the file will contain a record for the model "Apple "with the fields id, title and description.

Read new Apple from file:

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)

Write Apple with id 7 to a 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 to escape the linebreaks in your data if there are any possible..

Anyway it would be much easier to use 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)

All this worked in Rails 3, but remember, that you are saving the id as well, therefore saving and loading will cause the id to change, because a record with the given id already existed.

0

精彩评论

暂无评论...
验证码 换一张
取 消