Using ActiveResource to copy models with the same class?

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.

The problem I have at the start is that the models have the same
classname on both sites.

So while this works great in script/console running on
railsapp1.domain.com:

class Activity < ActiveResource::Base
self.site = “http://railsapp2.domain.com
end

activities = Activity.find(:all)

It’s not clear how I now get access to the local ActiveRecord class
called Activity on the running rails instance railsapp1.domain.com.

Has anybody tried doing this?

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs