I have an existing database structure created outside or Rails. I’ve edited one of the db/migrate files to include all the proper columns (not sure if this is the right way to do it) yet in the app or even in the interactive console, Rails is malforming the SQL necessary to query the table, specifically it is missing the ID column.
SELECT `dvds`.* FROM `dvds` WHERE (`dvds`.`` >= 0) ORDER BY `dvds`.`` ASC LIMIT 1000
I’ve also ran rake db:create after editing the migrate file with the proper column names and types.
How do I tell Rails what the current structure is?
This happened to me before and I think I had to end up deleting all the migrate files and generating some files from scratch. I honestly can’t remember what I did to fix it (should have written it down) but I’m sure there is a file I can edit to let Rails know the structure no?
Table schema:
`id` int(11) unsigned NOT NULL,
`title` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
`studio` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`released` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
`status` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
`sound` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`versions` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`price` varchar(10) CHARACTER SET utf8 DEFAULT NULL,
`rating` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`year` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
`genre` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`aspect` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`upc` varchar(155) CHARACTER SET utf8 DEFAULT NULL,
`dvd_realease` timestamp NULL DEFAULT NULL,
`timestamp` timestamp NULL DEFAULT NULL,
`directors` varchar(342) CHARACTER SET utf8 DEFAULT NULL,
`actors` varchar(342) CHARACTER SET utf8 DEFAULT NULL
Migrate file:
class CreateDvds < ActiveRecord::Migration
def change
create_table :dvds do |t|
t.integer :id
t.string :title
t.string :studio
t.string :released
t.string :status
t.string :sound
t.string :versions
t.string :price
t.string :rating
t.string :year
t.string :genre
t.string :aspect
t.string :upc
t.timestamp :dvd_release
t.timestamps
t.string :directors
t.string :actors
end
end
end
For this particular example single table/model you do not have to “tell” Rails about the current structure of your database. ActiveRecord will do this for you. There is no file you update for this to work.
Ensure the dvds table has a primary key of “id” then all you need to do is have ActiveRecord class of Dvd. Migrations are only required if you are updating the database in anyway (which it appears you are not).
This is a useful talk for using rails with legacy databases slidesha.re/NbOo1 He discusses a gem to allow rails to handle composite primary keys bit.ly/MvEYk