我发现了这个:http ://www.slideshare.net/napcs/rails-and-legacy-databases-railsconf-2009并按照他的建议创建 sql 视图来包装遗留表。
这是我以前在我的上运行的(我在 Limesurvey 之上添加了一个应用程序):
CREATE VIEW `users` AS
SELECT `uid` as `id`,
`users_name` as `username`,
`email` as `email`,
`password` as `encrypted_password`,
`full_name` as `full_name`,
`role_names` as `role_names`,
`parent_id` as `parent_id`,
`lang` as `lang`,
`one_time_pw` as `one_time_pw`,
`created` as `created_at`,
`modified` as `updated_at`
FROM `lime_users`;"
问题是您必须在 sql 视图中包含基表中没有默认值的所有列,以便您插入到视图中。这是将“丑陋”的列名规范化为对 Rails 友好的列名的好方法。
我的用户模型:
class User < ActiveRecord::Base
before_save :save_encrypted_password
self.primary_key = "id" # This needs to be declared, for some reason.
def sha2(password)
(Digest::SHA2.new << password).to_s
end
def valid_password?(password)
return false if encrypted_password.blank?
return Devise.secure_compare(sha2(password), self.encrypted_password)
end
protected
def save_encrypted_password
if password == password_confirmation
self.encrypted_password = sha2(password)
else
errors.add :password_confirmation, "has to match password"
end
end
end
反映在数据库中的模型约束(非空值、唯一值等)以避免更多陷阱也是一个好主意。(在阅读了近一个小时的晦涩错误消息后,才艰难地学会了这一点。)
希望这可以帮助。