Reputation: 441
Is there any to specify a different schema for an ActiveRecord model in Rails 3? The following used to work in Rails 2:
class Company < ActiveRecord::Base
set_table_name "hr.company"
end
This fails in Rails 3 with the message Table myapp.hr.company doesn't exist
.
The following works for simple models:
class Company < ActiveRecord::Base
establish_connection "hr"
set_table_name "company"
end
The problem with this approach is twofold: first, Rails creates a separate database connection for this model, imposing an additional overhead. Second, all queries are now invoked in the context of this connection, meaning that any joins back to the myapp
schema will break:
class Company < ActiveRecord::Base
establish_connection "hr"
set_table_name "company"
has_many :widgets # widgets table resides in myapp schema
end
This in turn will fail with Table hr.widgets doesn't exist
.
So, is there any way to achieve this in Rails 3?
Upvotes: 2
Views: 2145
Reputation: 1492
You can use abstract class and inherit from it:
app/models/db.rb
class Db < ActiveRecord::Base
establish_connection :db
self.abstract_class = true
end
app/models/post.rb
class Post < Db
set_table_name :notes
belongs_to :user
end
app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
end
config/database.yml
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
db:
adapter: sqlite3
database: db/db.sqlite3
pool: 5
timeout: 5000
In db.sqlite3 there is only notes
table.
Upvotes: 1