Rails 填充现有连接 Table

Rails Populate Existing Join Table

所以我有两个 table,一个客户 table 和一个公司 table。我还创建了一个空的 Employees table,我想将其用作连接 table.

这些是我的关联:(我希望客户与他们各自的公司关联)

class Company < ApplicationRecord
  has_many :employees
  has_many :customers, :through => :employees
end

class Customer < ApplicationRecord
  belongs_to :employees
end

class Employee < ApplicationRecord
  belongs_to :customer
  belongs_to :company
end

执行此操作的最佳方法在哪里?在我的 Customer#new 控制器中的方法中?我读到我需要使用 <<,但我不知道如何处理它。

您可以尝试将公司拜访客户委托给他们的员工:

customer.rb

delegate :company, to: :employee

现在只要你问客户他的公司,他就会让他的员工来处理。

这里需要用到逆关联的概念: class 客户 has_many :companies, :through => :employees