如何正确设置拥有并属于rails活动记录中的多个关联

时间:2018-05-04 17:37:12

标签: ruby-on-rails activerecord associations psql model-associations

我有3个表:TenantsLandlordsLeaseAgreements

用户可以是TenantLandlord

LeaseAgreement可以有多个Tenants,可以有多个Landlords

Tenant可以有多个LeaseAgreements。同样适用于Landlord

现在,我使用LeaseAgreement表作为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表格是否有Tenant列和Landlord列?如果是,那么如何从Landlords记录中检索所有Tenants或全部LeaseAgreement

1 个答案:

答案 0 :(得分:2)

如果您真的需要LeaseAgreement和租户/房东之间的关联为1对多而不是1-1,则需要两个额外的连接表:

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使用模型上的列来存储单个外键。