代码之家  ›  专栏  ›  技术社区  ›  AkaZecik MikeZ

具有现有模型名称的外键

  •  0
  • AkaZecik MikeZ  · 技术社区  · 6 年前

    我有以下迁移:

    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 回复  |  直到 6 年前
        1
  •  2
  •   ahawrylak    6 年前

    最合适的解决方案似乎是重命名外键列 customer customer_id ,但如果您确实需要将列命名为 顾客 ,只需更改关联的名称,因为这就是rails的困惑所在。例如:

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

    注意,当不能从关联名称推断类名时,必须使用 class_name: 'Customer'