Rails 3: alias_attribute and Unkown column error

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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?

回答1:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!