How to re-construct ActiveRecord from yaml

My controller rm_grants_controller.rb snip:
class RmGrantsController < ApplicationController
def dump
File.open(‘db/backup/rm_grants.yaml’, ‘w’) { |f| f.puts
RmGrants.find(:all).to_yaml }
end
end

This creates ‘db/backup/rm_grants.yaml’ whose content look like

  • !ruby/object:RmGrant
    attributes:
    key1: value1
    key2: value2
    key3: value3
    attributes_cache: {}

  • !ruby/object:RmGrant
    attributes:
    key1: value1
    key2: value2
    key3: value3
    attributes_cache: {}

Now, I want to reconstruct ActiveRecord from the yaml file, so in
rm_grants_controllers.rb
def load
records = YAML.load_file(‘db/backup/rm_grants.yml’)
records.each do |record|
@rm_grant = RmGrant.new(params[record])
@rm_grants.save!
end
end

But that doesn’t do what I hope, which is to re-create all the
records. All it does is create empty records.

puts record.inspect shows
#<YAML::Object:0x5d26950 @class=“RmGrant”, @ivars={“attributes_class”-

{}, “attributes”=>{“key1”=>“value1”, “key2”=>“value2”,
“key3”=>“value3”}}>

But I have no idea what this means nor how to decipher it.

On 30 Jul 2008, at 00:37, John Do wrote:


key2: value2
key3: value3
attributes_cache: {}

I’m guessing that this code has been slightly edited from what’s
actually in your app. Please be careful when you do this as errors
produced (or omitted) in the process (the code above contains several
typos and so) can make things very confusing.

I’m guessing you just want to dump the object attributes (ie the
database attributes). An active record object contains some other
instance variables that track a bunch of stuff, so you’re not dumping
quite what you want, so you probably want something like

RmGrant.find(:all).collect {|record| record.attributes}.to_yaml

Now, I want to reconstruct ActiveRecord from the yaml file, so in
rm_grants_controllers.rb
def load
records = YAML.load_file(‘db/backup/rm_grants.yml’)
records.each do |record|
@rm_grant = RmGrant.new(params[record])
@rm_grants.save!
end
end

I’m not entirely sure what you were thinking here. Why are you using
params at all?
This should just be @rm_grant = RmGrant.new(record) (assuming you’ve
made the change I suggested above)

Fred