【发布时间】:2021-12-31 13:40:12
【问题描述】:
我目前有一个用户模型
class User < ApplicationRecord
has_one :leases
end
租赁模式
class Lease < ApplicationRecord
belongs_to :tenant, class_name: 'User'
belongs_to :landlord, class_name: 'User'
end
和租赁模式
class Rental < ApplicationRecord
has_one :lease, dependent: :destroy
end
我只有一个用户模型支持租户和房东。
我面临的问题是房东可以与许多不同的租户签订多个租约,但租户一次只能拥有一个租约。
我对如何正确构建它感到有些困惑。我是否应该与 User 模型和 Lease 模型而不是 has_one 有一个 has_many 关系,然后只是一个方法说在 User 模型上租用来获得租户的租约? 我想要的是类似的东西
tenant.lease
和
landlord.leases
我可以吗?
class User < ApplicationRecord
has_one :lease, foreign_key: "tenant_id"
has_many :leases, foreign_key: "landlord_id"
end
这似乎可行,但我不确定它是否正确。
【问题讨论】:
-
如果你为租客和房东分开桌子,那会让你的生活更轻松,至少我会那样做。
-
您考虑过使用 STI 吗?这将启用多个类,每个类都有自己的
has_one或has_many,但它们会在后台使用同一个表。
标签: ruby-on-rails associations