I have a legacy SQL schema which looks something like this:
CREATE TABLE `User` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`userType` varchar(255) DEFAULT NULL,
`seqNo` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
CREATE TABLE `Employee` (
`userType` varchar(255) DEFAULT NULL,
`id` bigint(20) NOT NULL,
`employeeNumber` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `FKB65C8D4DB07F537D` (`id`),
CONSTRAINT `FKB65C8D4DB07F537D` FOREIGN KEY (`id`) REFERENCES `User` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In this design, an Employee i开发者_Go百科s-a User in the domain model. i.e. The employee's "id" field is a foreign key which references User.id.
How would I encode this relationship with Rails 3.0 models and migrations? For example, if I ran
rails g scaffold User userType:string seqNo:integer
it would get me a Rails database migration which would generate a very similar schema, and a model which could access that table. However I am not sure what to do to get the Employee table with Employee.id as a foreign key referring to User.id, as well as getting an Employee model which can access both tables.
How can I accomplish this?
There are a couple of options for Rails to use legacy database schemata, e.g. when defining your migration or when defining the relations.
Here are some pointers:
http://www.slideshare.net/napcs/rails-and-legacy-databases-railsconf-2009
http://www.killswitchcollective.com/articles/45_legacy_data_migration_with_activerecord
http://sl33p3r.free.fr/tutorials/rails/legacy/legacy_databases.html
http://lindsaar.net/2007/11/26/connecting-active-record-to-a-legacy-database-with-stored-procedures
http://pragdave.blogs.pragprog.com/pragdave/2006/01/sharing_externa.html
ActiveRecord Join table for legacy Database
I would also recommend the book "Pro Active Record" ... not sure if there is a newer edition for Rails 3.
It turns out that after running the scaffolds as follows:
rails g scaffold User userType:string seqNo:integer
rails g scaffold Employee id:integer userType:string employeeNumber:string
I would then have to edit the models to look like this:
class User < ActiveRecord::Base
has_one :employee
end
class Employee < ActiveRecord::Base
belongs_to :user, :foreign_key=>"id"
end
The only other thing to do is delete the generated migrations so that the database is not altered when rake db:migrate is called.
精彩评论