【问题标题】:Rails associations confusingRails 关联令人困惑
【发布时间】:2017-11-11 09:55:56
【问题描述】:

我有 4 个模型,分别是 CompanyCandidateJobApplication

对于Company

has_many :candidates
has_many :jobs

对于Candidate

belongs_to :company
has_one :application

对于Jobs

belongs_to :company
has_many :applications

对于Application

belongs_to :candidate
belongs_to :job

我不确定CandidateJobsApplication 之间的关系是否正确。如果有人可以提出一些改进建议,那就太好了。谢谢。

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    你在正确的轨道上。添加间接关联也可以让您向上和向下查询层次结构:

    class Company < ApplicationRecord
      has_many :jobs
      has_many :applications, through: :jobs
      has_many :candidates, through: :applications
    end
    
    class Job < ApplicationRecord
      belongs_to :company
      has_many :applications
      has_many :candidates, through: :applications
    end
    
    class Application  < ApplicationRecord
      belongs_to :candidate
      belongs_to :job
      has_one :company, through: :job
    end
    
    class Candidate < ApplicationRecord
      has_many :applications
      has_many :jobs, through: :applications
      has_many :companies, through: :jobs
    end
    

    【讨论】:

    • 另一个技巧是将您的示例编写为代码或元代码。我从来没有想过单独编写类名和内容,因为如果缩进正确,它更容易理解。
    【解决方案2】:

    我认为建立 activerecord 关联的最简单方法是想象您在现实生活中的关联。在这种情况下,一家公司有几个职位,每个职位有几个申请,每个申请有一个候选人。

    因此关系将是

    对于公司

    has_many :jobs
    

    为了工作

    belongs_to :company
    has_many :applications
    

    申请

    belongs_to :job
    has_one :candidate
    

    为候选人

    belongs_to :application
    

    【讨论】:

    • 我会提出申请belongs_to :canditate,因为这会让候选人申请不止一份工作。这意味着 OP 实际上做对了。
    • 我会为 Comapny 添加 has_many :applications, through: :jobshas_many :candidates, through: :applications
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2022-01-21
    • 2022-01-17
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多