Re: Using ActiveResource to copy models with the same class?

Stephen Bannasch
Tue, 22 May 2007 20:13:29 -0000

>I''d like to be able to copy model objects from one site instance of
>my rails application to another and I''m wondering if I can use or
>adapt ActiveRecord for this purpose.

I figured it out and I thought other people might like to know.

I''m using edge rails (rev 6786) checked out with Piston.

The following was all done in script/console.

First I put my ActiveResource classes in a Module so there wouldn''t be
any name space clash with the identically named existing local ActiveRecord
classes:

  module Remote
    class RemoteDiy < ActiveResource::Base
      self.site = "http://railsapp2.domain.com/"
    end
    class Level < RemoteDiy; end
    class Subject < RemoteDiy; end
    class Unit < RemoteDiy; end
  end

Then I just got the complete collections of levels, subjects, and units using a
syntax identical to ActiveRecord:

  levels = Remote::Level.find(:all); puts "copied: #{levels.length}"
  subjects = Remote::Subject.find(:all); puts "copied:
#{subjects.length}"
  units = Remote::Unit.find(:all); puts "copied: #{units.length}"

Finally I created local ActiveRecord objects with attributes of each remote
object.

  levels.each { |l| Level.create(l.attributes) unless
Level.find_by_name(l.attributes[''name'']) }; nil
  subjects.each { |s| Subject.create(s.attributes) unless
Subject.find_by_name(s.attributes[''name'']) }; nil
  units.each { |u| Unit.create(u.attributes) unless
Unit.find_by_name(u.attributes[''name'']) }; nil

Done! I like it!

I did this because I wanted to synch my development environment with copies of
data from the production application.

Now I need to learn more about how to use ActiveResource to create associations
and their attributes. Any pointers to working code would be greatly appreciated.
--
- Stephen Bannasch
  Concord Consortium, http://www.concord.org

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---