我有3个表:Tenants
,Landlords
,LeaseAgreements
用户可以是Tenant
或Landlord
。
LeaseAgreement
可以有多个Tenants
,可以有多个Landlords
。
Tenant
可以有多个LeaseAgreements
。同样适用于Landlord
。
现在,我使用LeaseAgreement
表作为Landlords
和Tenants
之间的联接:
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
?
答案 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使用模型上的列来存储单个外键。