Search code examples
ruby-on-railsrails-migrationsmodel-associations

Foreign key with a name of an existing model


I have the following migration:

class CreateTables < ActiveRecord::Migration[5.2]
  def change
    create_table "customers" do |t|
      t.string "name"
    end

    create_table "items" do |t|
      t.integer "customer"
    end
  end
end

and models:

class Customer < ApplicationRecord
  has_many :items, foreign_key: :customer
end
class Item < ApplicationRecord
  belongs_to :customer, foreign_key: :customer
end

The following code loops infinitely because the column used in foreign key has the same name as an existing model:

2.5.1 :001 > Customer.create(name: "John")
=> #<Customer id: 1, name: "John">

2.5.1 :002 > Customer.first
=> #<Customer id: 1, name: "John"> 

2.5.1 :003 > Customer.first.items
Traceback (most recent call last):
SystemStackError (stack level too deep)

How do I reference the column which name clashes with an existing name?


Solution

  • The most appropriate solution seems to be renaming foreign key column customer to customer_id, but if you REALLY need the column to be named customer, just change association's name, because that's where Rails gets confused. For example:

    class Item < ApplicationRecord
      belongs_to :item_customer, foreign_key: :customer, class_name: 'Customer'
    end
    

    Note, that when the class name can't be inferred from the association name, you have to specify it using class_name: 'Customer'