首页 > 解决方案 > Rails:我可以直接通过连接引用表吗?

问题描述

在我的应用程序中,我跟踪各种任务。每个任务都有一个person_id 引用一个persons 表。人员表引用公司表。通过这种方式,我可以查看每个任务的负责人以及他们所属的公司。

我的模型如下:

class Task < ApplicationRecord
  belongs_to :project
  delegate :workspace, :to => :project, :allow_nil => true
  belongs_to :person
  belongs_to :importance
  belongs_to :urgency
end

class Person < ApplicationRecord
  belongs_to :company
  has_many :tasks
end

class Company < ApplicationRecord
  has_many :people
end

我希望能够添加对我的任务表的引用,它允许我监视特定任务是哪个客户端。我可以创建一个名为 client 的新表并用所有客户端名称填充它。但是,由于我已经有公司表,这似乎是重复数据。因此,有没有办法让我在任务表中拥有 client_id 引用以及 person_id?我担心这会在我的控制器中引起问题,尤其是当我对某些数据运行查询时,因为每个任务都将属于一个客户,并且还有一个负责该任务的人很可能属于另一家公司。

标签: ruby-on-railsdatabasesqlite

解决方案


第一个选项,您创建客户表并执行以下关系,

class Task < ApplicationRecord
  belongs_to :project
  delegate :workspace, :to => :project, :allow_nil => true
  belongs_to :person
  belongs_to :client
  belongs_to :importance
  belongs_to :urgency
end


class Person < ApplicationRecord
  belongs_to :company
  has_many :tasks
  has_many :clients , :through => :tasks
end

class Client < ApplicationRecord
  belongs_to :company
  has_many :tasks
  has_many :people , :through => :tasks
end

class Company < ApplicationRecord
  has_many :people
  has_many :clients
end
  • task.client.company = 这将生成带有 client_id 的查询
  • task.person.company = 这将生成带有 person_id 的查询

第二个选项,我认为使用多对多自连接的更高级解决方案您只需将 client_id 添加到任务中,并且不需要创建客户端表,因为它将使用人员表

class Task < ApplicationRecord
  belongs_to :client, foreign_key: "client_id", class_name: "Person"
  belongs_to :person, foreign_key: "person_id", class_name: "Person"
end

class Person < ApplicationRecord
  # as person
    has_many: client_relations, foreign_key: :person_id, class_name: "Task"
    has_many: clients, through: :client_relations, source: :client
  # as client
    has_many: person_relations, foreign_key: :client_id, class_name: "Task"
    has_many: people, through: :person_relations, source: :person
end

推荐阅读