如何在 rails 活动记录中正确设置 has 和 belongs many association

How do I properly set up has and belongs to many association in rails active record

我有 3 个 table:TenantsLandlordsLeaseAgreements

用户可以是 TenantLandlord

一个LeaseAgreement可以有很多Tenants也可以有很多Landlords.

一个Tenant可以有多个LeaseAgreementsLandlord.

也是如此

现在,我正在使用 LeaseAgreement table 作为 LandlordsTenants 之间的连接:

class Tenant < ApplicationRecord
  belongs_to :user
  has_many :lease_agreements
  has_many :landlords, :through => :lease_agreements
end

class Landlord < ApplicationRecord
  include Token
  belongs_to :user
  has_many :lease_agreements
  has_many :tenants, :through => :lease_agreements
end

class LeaseAgreement < ApplicationRecord
  belongs_to :tenants
  belongs_to :landlords
end

我的 LeaseAgreement table 应该有一个 Tenant 列和一个 Landlord 列吗?如果是这样,那么我如何从 LeaseAgreement 记录中检索所有 Landlords 或所有 Tenants

如果您真的需要 LeaseAgreement 和 tenants/landlords 之间的关联是一对多而不是一对一,您需要两个额外的连接表:

class LeaseAgreement < ApplicationRecord
  has_many :lease_agreements_tenants
  has_many :tenants, through: :lease_agreements_tenants
  has_many :lease_agreements_landlords
  has_many :landlords, through: :lease_agreements_landlords
end

# rails g model LeaseAgreementTenant tenant:references lease_agreement:references
class LeaseAgreementTenant < ApplicationRecord
  belongs_to :tenant
  belongs_to :lease_agreement
end 

# rails g model LeaseAgreementLandlord landlord:references lease_agreement:references
class LeaseAgreementLandlord < ApplicationRecord
  belongs_to :landlord
  belongs_to :lease_agreement
end 

根据您的设置,每个 LeaseAgreement 只能有一个房东/租户,因为 belongs_to 使用模型上的一列来存储单个外键。