rails/rails — Issue #4836: establish_connection and self.table_name do not set arel_table and relation
Author: chadhinton
Created: 2012-02-01 22:46:48+00:00
State: open

I am calling establish_connection as described above but am still getting this error. I am using activerecord-sqlserver-adapter as the connection. It works on most calls but I discovered this error when hooking up kaminari or will_paginate:

## database.yml

```yaml
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000

my_db:
development:
adapter: sqlserver
host: mydbhost
database: mydb
username: myuser
password: mypass
```

## MyModel.rb

```ruby
class MyModel < ActiveRecord::Base
establish_connection Rails.application.config.database_configuration['my_db'][Rails.env]

self.table_name = 'dbo.mytable'
self.primary_key = :userid
end
```

## MyModelsController.rb:
```ruby
@users = MyModel.page(params[:page])
```

## index.html.erb

```ruby
<% @users.each do |user| %>
```

Relevant trace:
```ruby
Could not find table 'dbo.mytable'
activerecord (3.2.0) lib/active_record/connection_adapters/sqlite_adapter.rb:470:in `table_structure'
activerecord (3.2.0) lib/active_record/connection_adapters/sqlite_adapter.rb:379:in `primary_key'
arel (3.0.0) lib/arel/table.rb:39:in `primary_key'
activerecord-sqlserver-adapter (3.2.0) lib/arel/visitors/sqlserver.rb:169:in `visit_Arel_Nodes_SelectStatementWithOffset'
activerecord-sqlserver-adapter (3.2.0) lib/arel/visitors/sqlserver.rb:97:in `visit_Arel_Nodes_SelectStatement'
arel (3.0.0) lib/arel/visitors/visitor.rb:19:in `visit'
```

As you can see from the trace arel jumps back to sqlite_adapter instead of using activerecord-sqlserver-adapter causing the error. The arel table engine is set to ActiveRecord::Base.

To fix it I implicitly set the arel engine in the model:

## MyModel.rb
```ruby
class MyModel < ActiveRecord::Base
establish_connection Rails.application.config.database_configuration['my_db'][Rails.env]

self.table_name = 'dbo.mytable'
self.primary_key = :userid

@arel_table = Arel::Table.new(self.table_name, self)
@relation = ActiveRecord::Relation.new(self, @arel_table)
end
```

That works.