Rails:我可以直接通过联接引用表吗?

时间:2018-12-24 07:22:15

标签: ruby-on-rails database sqlite

在我的应用中,我跟踪各种任务。每个任务都有一个引用人员表的person_id。人员表引用公司表。这样,我可以看到每个任务的负责人以及他们所属的公司。

我的模型如下:

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的新表,并用所有客户端名称填充它。但是,因为我已经有了companies表,所以这似乎是在重复数据。这样,有没有办法让我在任务表中包含client_id引用以及person_id?我担心这会引起问题,尤其是在我对某些数据进行查询时,在控制器中,因为每个任务都属于一个客户,并且还有一个负责该任务的人员,很可能属于另一个公司。

1 个答案:

答案 0 :(得分:0)

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

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