【问题标题】:How to use ActiveRecord to create a has_many relationship without a bridge table如何在没有桥接表的情况下使用 ActiveRecord 创建 has_many 关系
【发布时间】:2015-12-21 07:12:57
【问题描述】:

对不起,这个很难在标题中表达。所以这就是我想要做的。一个车间有很多区。每个区只有一个 District_contact(实际上是一个 District_contact_id)。如何使用 ActiveRecord 来建模车间和 District_contact 之间的关系?我希望能够做到这一点:

Workshop.district_contacts

并获取实际用户对象的集合。现在,我用一个简短的函数完成了它:

  def district_contacts
    district_ids = []
    self.districts.each do |district|
      if district.contact_id
        district_ids << district.contact_id
      end
    end
    User.find(district_ids)
  end

【问题讨论】:

  • 您可以使用地图简化此功能。所以 District_ids = self.districts.map(&:contact_id)

标签: ruby-on-rails ruby activerecord orm data-modeling


【解决方案1】:

您的模型关联应如下所示。

class Workshop < ActiveRecord::Base
  has_many :districts
  has_many :district_contacts, through: disctricts
end

class District < ActiveRecord::Base
  belongs_to :workshop
  has_one :district_contract
end  

【讨论】:

    【解决方案2】:

    在 Workshop 模型中定义关联:

    has_many :districts
    has_many :district_contacts, through: disctricts
    

    【讨论】:

    • 显然我无法进行单个字符编辑,但您在最后几个区中添加了一个额外的“c”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2017-02-23
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多