我目前有一個用戶模型
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
這似乎有效,但我不確定它是否正確。
uj5u.com熱心網友回復:
使用STI,您可以擁有以下模型
==> user.rb <==
class User < ApplicationRecord
end
==> landlord.rb <==
class Landlord < User
has_many :leases
end
==> tenant.rb <==
class Tenant < User
has_one :lease
end
==> lease.rb <==
class Lease < ApplicationRecord
belongs_to :tenant
belongs_to :landlord
end
然后你可以做這樣的事情
irb(main):003:0> landlord = Landlord.create(name: 'the landlord')
=> #<Landlord id: 5, name: "the landlord", type: "Landlord", created_at: "2022-01-03 22:16:56", updated_at: "2022-01-03 22:16:56">
irb(main):004:0> tenant = Tenant.create(name: 'the tenant')
=> #<Tenant id: 6, name: "the tenant", type: "Tenant", created_at: "2022-01-03 22:17:09", updated_at: "2022-01-03 22:17:09">
irb(main):005:0> lease = Lease.create(tenant: tenant, landlord: landlord)
=> #<Lease id: 3, tenant_id: 6, landlord_id: 5, created_at: "2022-01-03 22:17:28", updated_at: "2022-01-03 22:17:28">
irb(main):006:0> tenant.lease
=> #<Lease id: 3, tenant_id: 6, landlord_id: 5, created_at: "2022-01-03 22:17:28", updated_at: "2022-01-03 22:17:28">
irb(main):007:0> landlord.leases
=> #<ActiveRecord::Associations::CollectionProxy [#<Lease id: 3, tenant_id: 6, landlord_id: 5, created_at: "2022-01-03 22:17:28", updated_at: "2022-01-03 22:17:28">]>
為此,您只需要向模型中添加一type列User,Rails 會負責其余的作業。
uj5u.com熱心網友回復:
在我看來,你應該采用has_many方法。由于房東和租戶都是用戶。代替使用tenant_idand landlord_id,您必須使用“user_id”并識別用戶,使用 user_type 即租戶和房東。
只是一個意見!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/402715.html
標籤:
下一篇:資料結構復習題
