【问题标题】:How to associate two models in two ways: many :through?如何以两种方式关联两个模型:许多:通过?
【发布时间】:2013-11-13 17:44:08
【问题描述】:

在使用 Rails 3.2.15 的政治分析应用程序中,我有一个 Candidate 模型和一个 District 模型。以下是我尝试建模的关系的细分:

  1. 候选人属于地区,因为他们在特定地区竞选公职。
  2. 一名或多名候选人也可以在他们的选区任职。
  3. 一位现任者是学区的“主要现任者”。

我是这样想的:

class District
  has_many :candidates
  has_many :candidates, :through => :incumbencies
end

class Candidate
  belongs_to: District
end

class Incumbency
  belongs_to :district
  belongs_to :candidate
  # This model has a boolean attribute :is_primary to distinguish primary incumbencies
end

这是正确的方法,还是我会遇到问题?感谢您的帮助。

编辑:

这里有一个例子来说明:

在 1 区

  • 候选人 1 是主要在职人员
  • 候选人 2 现任
  • 候选人 3 是候选人
  • 候选人 4 是候选人

在第 2 区

  • 候选人 5 是候选人
  • 候选人 6 是候选人

在第 3 区

  • 候选人 7 是主要在职人员
  • 候选人 8 是候选人

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    一切看起来都井井有条,但我认为 Incumbencies belongs_to :candidates 可能存在问题,但候选人没有任何在职。我认为如果你有它可能会更好:

    class District
      has_many :candidates
      has_many :incumbencies, :through => :candidates
    end
    
    class Candidate
      belongs_to :district
      has_one :incumbency
    end
    
    class Incumbency
      belongs_to :district
      belongs_to :candidate
      # This model has a boolean attribute :is_primary to distinguish primary incumbencies
    end
    

    我可能不正确地理解你们的关系,但似乎一个候选人可以有也可以没有一个在职,而且该学区有很多候选人,其中一些是在职的。

    【讨论】:

    • 谢谢!我只是添加了几个例子来澄清这些情况。这段代码是否描述了它们?
    • 我相信,你所有的例子都应该适合这个代码结构。唯一棘手的部分是当您尝试为给定地区拉出主要现任者时,但只要您正确设置查询,一切都会好起来的。
    • 您能否更具体地说明棘手部分的含义?我认为您的意思是找出一个地区的哪些在职人员将 is_primary 设置为 true。我可以做类似 my_district.incumbencies.where("is_primary == true") 的事情吗?
    • 查询不是我的强项,所以这可能就是我认为它很棘手的原因。这就是我尝试的方式,但我不能确定它是否正确。 my_district.joins(:incumbencies).where("incumbencies.is_primary ?", true)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多