建模许多Rails关联

我试图围绕如何为具有许多has_one关联(20+)的父模型建模我的数据库。 我有一个名为House的模型,它是所有其他模型的父模型:

class House < ActiveRecord::Base has_one :kitchen has_one :basement has_one :garage has_one :common_room #... Many other child models end 

所有子模型都包含特定于其自己类的唯一属性。 我考虑过STI,但实际上并没有任何可以在模型中使用的共享function或输入。 我还想过制作一个“超级模型”,但这并不是真正遵循Rails最佳实践,而且它将包含200多个列。 是否有其他设计模式或结构可用于高效建模,以便减少数据库调用?

 class House has_many :rooms Room::TYPES.each do |room_type| has_one room_type, -> { where(room_type: room_type) }, class_name: "Room" end class Room belongs_to :house TYPES = %i/kitchen basement garage common_room etc/.freeze end 

在迁移中,请确保add_index :rooms, [:type, :house_id], unique: true 。 除非房子可以有超过1种类型的房间。 如果是这种情况,我认为需要采用不同的方法。

对于你的第二个问题,它实际上取决于你使用什么类型的数据库? 如果它的PostgreSQL你可以使用hstore并将它们存储为属性哈希。 或者您可以序列化db以将其作为哈希值。 或者你可以有另一个房间有很多的模型。 例如has_many:properties并创建一个存储该信息的属性模型。 真的取决于你想要对信息做什么

为什么不在Rails中使用多态? 这会简单得多

 class House < ActiveRecord::Base has_many :properties, as: :property_house end class Kitchen < ActiveRecord::Base belongs_to :property_house, polymorphic: true end class Garage < ActiveRecord::Base belongs_to :property_house, polymorphic: true end 

有关更多信息,请访问: http : //terenceponce.com/blog/2012/03/02/polymorphic-associations-in-rails-32/