Modelling Many Rails Associations

2019-06-13 06:36发布

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

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?

2条回答
小情绪 Triste *
2楼-- · 2019-06-13 06:55
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

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.

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

查看更多
来,给爷笑一个
3楼-- · 2019-06-13 06:57

Why not using Polymorphism in Rails? It would be much simpler

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

For more information, go here: http://terenceponce.com/blog/2012/03/02/polymorphic-associations-in-rails-32/

查看更多
登录 后发表回答