使用foreigner gem指定自定义外键列名

时间:2013-10-15 12:32:16

标签: mysql ruby-on-rails rails-migrations foreigner

我有2个模型,员工和用户具有has_one,belongs_to关系。用户表有一个“登录”列,只需要来自employee表的'emp_id'值。我尝试通过以下迁移来捕获这种关系:

      class AddFkToUsers < ActiveRecord::Migration
            def change
            add_foreign_key( :users, :employees, :source_column => :login, :foreign_column 
         => :emp_id )
            end
        end

但是当我尝试运行此迁移时,我收到错误消息:

    Mysql2::Error: Key column 'employee_id' doesn't exist in table: ALTER TABLE `users` 
    ADD CONSTRAINT `users_employee_id_fk` FOREIGN KEY (`employee_id`) REFERENCES 
   `employees`(id)/home/vasu/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-
    3.2.9/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `query'

我以为我也可以指定外来列名,这不可能吗?

1 个答案:

答案 0 :(得分:0)

至少对于外国人版本1.6.0我相信你的案例的正确语法是:

add_foreign_key(:users, :employees, :column => 'login', :primary_key => 'emp_id')