【问题标题】:Rails Populate Existing Join TableRails 填充现有连接表
【发布时间】:2017-08-15 17:06:28
【问题描述】:

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

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

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 属于还是有很多employeesemployee 是否属于或拥有一个 customer?现在你有belongs_to 双向

标签: ruby-on-rails postgresql jointable


【解决方案1】:

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

【讨论】:

  • 我需要通过迁移添加 customer_id 列和 company_id 列还是自动添加?
  • 您将始终需要在连接表中添加列(在您的情况下为员工)。始终需要迁移来支持您的 ActiveRecord 关联。
  • 非常感谢。目前正在学习 Rails,并正在尝试做一些更“复杂”的数据库关系。你帮了很多忙。
  • 随时为您提供帮助 :) 您也可以 PM 我寻求帮助
【解决方案2】:

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

客户.rb

delegate :company, to: :employee

现在,每当您向客户询问其公司时,它都会要求其员工处理。

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2016-01-09
    • 2017-09-25
    • 2014-01-03
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多