16

I'm re-doing an app and migrating data from an old app. The some of the models names will be the same, though not all of them.

I'm writing a rake task to connect to the old database, read the records, do some stuff and write the result into a new database. Because some of the table names are the same the model names will be the same, so I want to name space my models like so

module OldData
    class Account <ActiveRecord::Base
      has_many :subcriptions
      establish_connection $olddb  
    end

    class Subscription <ActiveRecord::Base
      belongs_to :account
      establish_connection $olddb  
    end
end

where $olddb is a hash required to connect to the old database

I can open account records and read them ok, but the Account model doesn't have a subscriptions association. The latest Rails documentation suggest that this should work. but it doesn't.

Any advice?

John Small
  • 942
  • 2
  • 12
  • 21
  • If you follow the convention and put each model in a separate file named after that model, there's high chance it will work. – RocketR Jul 08 '13 at 09:06

1 Answers1

35

maybe you should try to set class name explicitly

has_many :subcriptions, class_name: 'OldData::Subscription'

and

belongs_to :account, class_name: 'OldData::Account' 
  • 10
    This is not necessary if both models are in the same namespace. – RocketR Jul 08 '13 at 09:08
  • Actually you're right. But for some reason you need to explicitly specify namespace if the model is custom namespace. Maybe it's a bug? Or maybe I missing something. – Rostyslav Diachok Jul 08 '13 at 18:41
  • What do you mean by custom namespace? If I have `Persistent::Post` and `Persistent::Comment` then simply `Post.has_many :comments`. Works without the `class_name` option. Maybe we're using different Rails versions (I'm on 4.0.0)? – RocketR Jul 09 '13 at 12:01
  • 2
    I had two models not in the same namespace and this answer saved my bacon. Thank you! – Nick Schwaderer Feb 13 '17 at 13:34