简体   繁体   中英

How to use an existing Postgres table in Rails 3

I'm completely new to Rails, but I've done quite a bit of searching and nothing has successfully addressed this issue. It seems like a simple one.

I am using Netbeans, if that makes a difference.

I have a Postgres database called diagnostics Inside of which is a table called diagnostics_data . It is filled with data. Quite a lot of it, which is generated by another application and updated daily. There are a couple hundred columns that will be changing from time to time. My rails application will simply take that data, and plot it in a dynamic web environment. I have the plotting routines figured out in a sample DB I made in Rails, but I don't know how to get Rails to use the existing table.

I have created a new application, and updated the schema.rb using which looks like:

ActiveRecord::Schema.define(:version => 20120224014811) do
create_table "diagnostics_data", :force => true do |t|
t.string "orbit_number",                                  :limit => nil
t.string "netcdf_location",                               :limit => 300

This seems to indicate that I have successfully connected to the correct database. I have even generated a model and migration for Diagnostics_Data but...

>>ActiveRecord::Base.connection.tables
>>   []

yields nothing. I do have a generated model

class DiagnosticsData < ActiveRecord::Base
end

But I can't connect to the actual table

>>d=DiagnosticsData.first
>>   ActiveRecord::StatementInvalid: Could not find table 'diagnostics_data'

So even if I have to start from scratch, how do I get rails to connect to an existing table, specifically, I'd like to use this in a simple scaffold, so I can just drop my sample code to use the Model from my table with some cool Views and Controllers.

So when you use rails with an existing database after editing the database.yml file you don't need to muck about in the schema file.

Just open up your model file and do something like this

class Mammals < ActiveRecord::Base
  set_table_name "tbl_Squirrels"
  set_primary_key :squirrel_id
end

you can specify all of the column names in here too if you want to reference them the way that you wrote in the sample code.

There is some magic here with what rails does with names like "Id" will automatically be the primary key unless otherwise specified. as well as "tablename_id" will be a foreign key to tablename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM