Hi there Im a beginner to rails and what Im doing seems a common usecase to me yet, its funny it seems so hard to do in Rails and not many posts on the internet about the topic:
-
I created a new rails app. Since I had a legacy database that I wanted to include in my new rails app, I replaced the “development.sqlite3” with the legacy database “Listings.sqlite3”
-
Then I generated a model “business.rb” to match the table “Businesses” in my legacy db. Here is the code for it:
class Business < ActiveRecord::Base establish_connection "Listings_development" end -
Then I modified the “config/database.yml” file to include the following:
Listings_development: adapter: sqlite3 database: db/Listings.sqlite3 pool: 5 timeout: 5000 Listings_test: adapter: sqlite3 database: db/Listings.sqlite3 pool: 5 timeout: 5000 Listings_production: adapter: sqlite3 database: db/Listings.sqlite3 pool: 5 timeout: 5000 -
After that I generated the controller called “businesses_controller.rb” which has the following code:
class BusinessesController < ApplicationController def show end def index @businesses = Business.all respond_to do |format| format.html #index.html.erb end end end -
Finally I changed the “config/routes.rb” file to the following:
Directory::Application.routes.draw do resources :businesses get "business/index" match ':controller(/:action(/:id))(.:format)' -
Lastly I added a view file “index.html.erb:
<h1>Listing businesses</h1> <table> <tr> <th>Name:</th> <th>Phone Number:</th> <th>Address:</th> </tr> <% @businesses.each do |business| %> <tr> <td><%= business.company_name %></td> <td><%= business.phone_number %></td> <td><%= business.address %></td>
I thought I was done, I had successfully managed to incorporate my legacy database and its data in my new rails app. But when I typed in “http://localhost:3000/businesses/” in my browser window. I get this error on the screen:
Showing /Users/AM/Documents/RailsWS/cmdLineWS/Directory/app/views/businesses/index.html.erb
where line #14 raised:
undefined method `company_name' for #<Business:0x00000104e1d0e8>
Extracted source (around line #14):
11:
12: <% @businesses.each do |business| %>
13: <tr>
14: <td><%= business.company_name %></td>
15: <td><%= business.phone_number %></td>
16: <td><%= business.address %></td>
17: <td><%= link_to 'Show', business %></td>
Rails.root: /Users/AM/Documents/RailsWS/cmdLineWS/Directory
Whats up with Rails?? Is it really that complex to include a legacy db? I thought the whole point of rails was rapid prototyping.
Here is a snapshot of my Listings.db file

The problem could be caused by the fact the businesses’ columns contains spaces and uppercase chars (e.g. I see “Company Name” in the screenshot instead of the wanted “company_name”). I don’t know if rails support this kind of attribute names.
BTW is not a good practice have spaces and other strange characters in column names (in my humble opinion)