I am using Devise for authentication, so I’ve aliased a few columns in my legacy database to accommodate it as follows:
class User < ActiveRecord::Base
set_table_name 'my_legacy_user_table'
set_primary_key 'UserId'
alias_attribute :id, :UserId
alias_attribute :username, :LoginId
alias_attribute :encrypted_password, :PasswordSHA1Hash
alias_attribute :first_name, :Name
alias_attribute :last_name, :Surname
devise :database_authenticatable, :authentication_keys => [:username]
attr_accessible :username, :password, :password_confirmation
def password_salt=(password_salt)
end
def password_salt
end
def password_digest(password)
self.class.encryptor_class.digest(password)
end
end
When I post to my /users/sign_in form, I get the following exception:
Mysql2::Error: Unknown column 'my_legacy_user_table.username' in 'where clause': SELECT `kms_User`.* FROM `my_legacy_user_table` WHERE (`my_legacy_user_table`.`username` = 'mrichman') LIMIT 1
I suppose I was under the assumption that alias_attribute would instruct ActiveRecord to use the real column name (UserId) and not the alias (username). What am I doing wrong?
Arel (the one that makes the SQL queries) still is not aware of ActiveRecord’s aliases (up to 3.0.3). You should make sure that the query is made using the original name, LoginId, in this case.
If you enter the console and make a User.where(:username => “root”) you see that it generates an error, although User.username works well.
For now just replace the username occurrences on sinup form until the upstream starts to support it.
EDIT: By the way, the recommended way of doing that is make a view! Don’t forget that!
http://www.slideshare.net/napcs/rails-and-legacy-databases-railsconf-2009