具有现有模型名称的外键

时间:2018-06-17 13:01:06

标签: ruby-on-rails rails-migrations model-associations

我有以下迁移:

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

和模特:

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

以下代码无限循环,因为foreign key中使用的列与现有模型具有相同的名称:

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)

如何引用名称与现有名称冲突的列?

1 个答案:

答案 0 :(得分:2)

最合适的解决方案似乎是将外键列customer重命名为customer_id,但如果您真的需要将列命名为customer,只需更改关联的名称,因为这就是Rails感到困惑。例如:

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

请注意,当无法从关联名称推断出类名时,您必须使用class_name: 'Customer'

指定它
相关问题