简体   繁体   English

Rails HABTM还是has_many?

[英]Rails HABTM or has_many?

I have two models: Person, and Property. 我有两个模型:Person和Property。 In the Person model I have a field which stores the role of the person(tenant, owner, admin, contractor, etc). 在人员模型中,我有一个存储人员角色(租户,所有者,管理员,承包商等)的字段。 Since each property will belong to an owner and potentially have one or more tenants, I thought this would be a good opportunity to use the HABTM model relation. 由于每个财产将属于一个所有者,并且可能有一个或多个租户,因此我认为这将是使用HABTM模型关系的好机会。

Do I have this right? 我有这个权利吗?

Also, how do I reference the attached model? 另外,如何参考附件中的模型? Assuming my join model is named PropertiesPeople, and I wanted to fetch the tenants for a particular property, would that be the following? 假设我的加入模型命名为PropertiesPeople,并且我想获取特定属性的租户,那将是以下情况吗?

@property.people.where(:role => "tenant")

If the same Person can have more than one Property, you should can use HABTM. 如果同一个人可以拥有多个财产,则应该使用HABTM。 Something like this: 像这样:

class Person < ActiveRecord::Base
  # in the people table you are storing the 'role' value
  has_and_belongs_to_many :properties, join_table: 'people_properties'
end

class Property < ActiveRecord::Base
  has_and_belongs_to_many :people, join_table: 'people_properties'
end

You should create the intermidiate table people_properties with the foreign keys, person_id and property_id . 您应该使用外键person_idproperty_id创建中间表people_properties

The problem of this approach is that if a Person can be "tenant" in one property and "contractor" in another, for example, you can't store that information. 这种方法的问题在于,例如,如果某个人可以在一个资产中成为“承租人”,而在另一个资产中成为“承包人”,则您将无法存储该信息。 In that case I will suggest using an intermidiate model, like this 在这种情况下,我建议使用像这样的中间模型

class Person < ActiveRecord::Base
    has_many :property_people
    has_many :properties, through: :property_people
end

class PropertyPerson
    # now you store here the 'role' value
    belongs_to :person
    belongs_to :property
end

class Property < ActiveRecord::Base
    has_many :property_people
    has_many :people, through: :property_people
end

I don't know for sure if the class names are successfully inferred from the relationships names, in that case you can always indicate class_name or even the foreign_key for the associations. 我不确定从关系名称中是否成功推断出了类名,在这种情况下,您始终可以为关联指定class_nameforeign_key Also you can indicate the table for a model, using self.table_name= 您也可以使用self.table_name=指示模型表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM