`connects_to` can only be called on ActiveRecord::Base or abstract classes

Viewed 1519

In my Ruby on Rails application I want to access some data from a second, non-standard (not complying to Rails conventions) database. The Ruby on Rails application should only read, but not write to this database.

In config/database.yaml I declare it like this:

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

wn:
  <<: *default
  database: ~/dev/wn/wn.db

Then, I added the following class to app/models directory:

class CiHarvestRecord < ActiveRecord::Base
  self.table_name = "ciHarvest"
  connects_to database: { reading: :wn }
end

When I add the code

<% harvest_item = CiHarvestRecord.first
harvest_item 

   %>

and open the respective page, I get the error connects_to can only be called on ActiveRecord::Base or abstract classes`.

How can I fix it, i. e. tell Rails that CiHarvestRecord is located a different (wn) database?

I am using Ruby 2.6.3 and Rails 6.1.3 on MacOS Big Sur.

Update 1: If I add the file app/models/wn.rb with the contents

class Wn < ActiveRecord::Base
  self.abstract_class = true
  connects_to database: { reading: :wn }
end

then renamed CiHarvestItem.rb to ci_harvest_item.rb and now it contains this:

class CiHarvestRecord < Wn
  self.table_name = "ciHarvest"
end

Now I am getting the error No connection pool for 'Wn' found..

Update 2:

I ran

cd db
ln -s ~/dev/wn/wn.db wn.db

then changed database.yaml to

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

wn:
  <<: *default
  database: db/wn.db

But I am still getting the same error as in update 1.

2 Answers

Create an abstract class in models/wn.rb ...

class Wn < ActiveRecord::Base
  self.abstract_class = true
  connects_to database: { reading: :wn }
end

then in models/ci_harves_record.rb

class CiHarvestRecord < Wn
  self.table_name = "ciHarvest"
end
Related