Rails associations in namespaced models
Asked Answered
R

1

17

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?

Roofer answered 1/6, 2013 at 14:56 Comment(1)
If you follow the convention and put each model in a separate file named after that model, there's high chance it will work.Teddytedeschi
U
36

maybe you should try to set class name explicitly

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

and

belongs_to :account, class_name: 'OldData::Account' 
Unwelcome answered 1/6, 2013 at 15:5 Comment(4)
This is not necessary if both models are in the same namespace.Teddytedeschi
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.Unwelcome
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)?Teddytedeschi
I had two models not in the same namespace and this answer saved my bacon. Thank you!Barret

© 2022 - 2024 — McMap. All rights reserved.