Как правильно настроить имеет и принадлежит многим ассоциациям в рельсах активной записи - PullRequest
0 голосов
/ 04 мая 2018

У меня есть 3 таблицы: Tenants, Landlords, LeaseAgreements

Пользователь может быть Tenant или Landlord.

A LeaseAgreement может иметь много Tenants и может иметь много Landlords.

A 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 записи?

1 Ответ

0 голосов
/ 05 мая 2018

Если вам действительно нужно, чтобы связи между 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 может быть только один арендодатель / арендатор, так как own_to использует столбец в модели для хранения одного внешнего ключа.

...