建模许多轨道协会 [英] Modelling Many Rails Associations

查看:83
本文介绍了建模许多轨道协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to wrap my head around how I should model my database for a parent model with many has_one associations (20+). I have one model called House which is the parent model of all the other models:

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

所有子模型都包含特定于其自己类的唯一属性。我已经考虑过STI,但是并没有真正的任何共享功能或者可以在模型中使用的输入。我也想过制作一个'超级模特',但是并不是真的遵循Rails的最佳做法,加上它将包含200列。是否有另一种设计模式或结构,我可以使用它来有效地建模,以便我可以减少数据库调用?

All the child models contain unique properties specific to their own class. I've thought about STI, but there isn't really any shared functionality or inputs that I can use across models. I've also thought of making one 'super model', but that doesn't really follow Rails best practices, plus it would contain over 200 columns. Is there another design pattern or structure that I can use to model this efficiently so that I can reduce database calls?

推荐答案

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种类型的房间。如果是这样,我认为需要一种不同的方法。

In your migration make sure to add_index :rooms, [:type, :house_id], unique: true. Unless a house can have more than 1 type of room. If that is the case, I think a different approach is needed.

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

To your second question, it depends really, what type of database are you using? If its PostgreSQL you could use hstore and store those as a properties hash. Or you could serialize you db to take that as a hash. Or you could have another model that room has many of. For instance has_many :properties and make a property model that would store that information. Really depends on what else you want to do with the information

这篇关于建模许多轨道协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆