Question

I have 2 models, employee and user with a has_one, belongs_to relationship. The user table has a 'login' column which needs to only be the 'emp_id' value from the employee table. I tried to capture this relationship with the below migration:

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

but when i try to run this migration I get an error msg:

    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'

I thought I could specify the foreign column name too, is this not possible?

No correct solution

OTHER TIPS

At least for foreigner version 1.6.0 I believe the correct syntax for your case is:

add_foreign_key(:users, :employees, :column => 'login', :primary_key => 'emp_id')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top