在 Rails 4 中同时使用 POLYMORPHIC 和 :THROUGH 关联?
Using POLYMORPHIC and :THROUGH association at the same time in Rails 4?
我在 Rails 中遇到了更高级的关联问题。
这是我想要做的:
房东可以创建很多房产,而且都属于房东
每个属性可以有多个租户,每个租户只能属于一个属性。
房东应该能够在他各自的 属性.
中对新租户使用 CRUD
租户只能看到attributes/status与自己相关的属性
这是我认为应该如何布局的
class User < ActiveRecord::Base
belongs_to :tenant, polymorphic: true
end
class Property < ActiveRecord::Base
has_many :users, as: :tenant
belongs_to :landlords
end
class Landlord < ActiveRecord::Base
has_many :property
has_many :users, as: :tenant, through: :properties
end
这是正确的吗?
是不是better/less没有多态关联就绕了,直接用through关联?
我会这样做:
class Landlord
has_many :properties
has_many :tenants, through: :properties
end
class Tenant
belongs_to :property
belongs_to :landlord, through: :properties
end
class Property
belongs_to :landlord
has_many :tenants
end
查看此active record associations guide了解更多信息。
我在 Rails 中遇到了更高级的关联问题。
这是我想要做的:
房东可以创建很多房产,而且都属于房东
每个属性可以有多个租户,每个租户只能属于一个属性。
房东应该能够在他各自的 属性.
中对新租户使用 CRUD
租户只能看到attributes/status与自己相关的属性
这是我认为应该如何布局的
class User < ActiveRecord::Base
belongs_to :tenant, polymorphic: true
end
class Property < ActiveRecord::Base
has_many :users, as: :tenant
belongs_to :landlords
end
class Landlord < ActiveRecord::Base
has_many :property
has_many :users, as: :tenant, through: :properties
end
这是正确的吗?
是不是better/less没有多态关联就绕了,直接用through关联?
我会这样做:
class Landlord
has_many :properties
has_many :tenants, through: :properties
end
class Tenant
belongs_to :property
belongs_to :landlord, through: :properties
end
class Property
belongs_to :landlord
has_many :tenants
end
查看此active record associations guide了解更多信息。