Ruby on rails 如何在rails中优雅地建模许多具有细微差异的相似资源
对数据库的整个网络编程还是很陌生的,很高兴你能给我一些提示 现在,我一直在想这个问题,但我似乎找不到一个优雅的解决方案 假设我有一家有几层楼的酒店,例如一楼、二楼、三楼 假设每层楼都有几种类型的套房,例如总统套房、蜜月套房、皇帝套房。每个套房都有许多属于它的房间。房间本身在家具方面各不相同 现在,每种类型的套房都可以在一层或多层的多个套房中找到Ruby on rails 如何在rails中优雅地建模许多具有细微差异的相似资源,ruby-on-rails,database-design,model,Ruby On Rails,Database Design,Model,对数据库的整个网络编程还是很陌生的,很高兴你能给我一些提示 现在,我一直在想这个问题,但我似乎找不到一个优雅的解决方案 假设我有一家有几层楼的酒店,例如一楼、二楼、三楼 假设每层楼都有几种类型的套房,例如总统套房、蜜月套房、皇帝套房。每个套房都有许多属于它的房间。房间本身在家具方面各不相同 现在,每种类型的套房都可以在一层或多层的多个套房中找到 +1stFloor +president suite +room1 +room2 +honeymoon suite
+1stFloor
+president suite
+room1
+room2
+honeymoon suite
+room1
+2ndFloor
+president suite
+room1
+room2
+emperor suite
+room1
+room2
+room3
+3rdFloor
+emperor suite
+room1
+room2
+room3
+honeymoon suite
+room1
所以我可以从地板模型开始,接着是属于地板的套房模型和属于套房的房间模型。也许房间里有不同类型的家具,所以房间1、2和3并不相似,尽管房间1和不同的房间1是相似的。这变得非常复杂,我不确定我是否做得对
另一种方法是将每个套件建模为一个完整的独立资源
关于如何做这件事有什么建议吗
- 我是否为每个套房建立了一个单独的模型,尽管它们在属性上相似,但房间的数量和类型不同。一旦您拥有100多个不同的套件,它似乎非常重复且容易出错
- 我是否构建独立的资源,如楼层、套房、房间,并逐一实例化和关联它们?我会知道怎么做,这样我就可以建造总统套房了。但是,当我需要不止一间总统套房时,如何建立相同的套房/房间关联
- 当房间除了一件零碎的家具外,其他大部分属性都相同时,我该如何对房间进行建模
蒂姆你需要这样的东西:
class Room < ActiveRecord
belongs_to :suite
validates :suite, presence: true #make sure room is not a rouge entry
validates :floor_num, presence: true
end
class Suite < ActiveRecord
has_many :rooms, dependent: :destroy
validates :type, presence: true
end
编辑:
例如,对于不同房间的家具,最好的方法是创建另一个模型
class Room < ActiveRecord
...
has_many :furniture
...
end
class Furniture < ActiveRecord
belongs_to :room
validates :room, presence: true
validates :name, presence: true
end
又一次编辑
当然,如果房间里有家具,那就意味着套房里也有家具,所以你唯一需要做的就是像这样在套房类中增加一个关联
class Suite < ActiveRecord
...
has_many :furniture, through: :rooms
...
end
编辑:例如,如果您需要楼层包含的房间多于房间,则需要使用多态关联。很好地解释了如何使用这些:)
希望这能回答您的问题:)祝您学习rails好运:)看一看,这是一个结构良好、内容丰富的地方。我想可能是这样的
class Floor < ActiveRecord::Base
has_many :suites
end
class Suite < ActiveRecord::Base
belongs_to :floor
belongs_to :suite_category
has_many :rooms, :dependent => :destroy
end
class SuiteCategory < ActiveRecord::Base
has_many :suites
end
class Room < ActiveRecord::Base
belongs_to :suite
has_and_belongs_to_many :room_types
end
class RoomType < ActiveRecord::Base
has_and_belongs_to_many :rooms
end
课堂:毁坏
结束
类SuiteCategory
这样,您就可以拥有许多具有不同家具配置的房间类型,并将您的房间与之关联。有点像标签。非常感谢您的快速回答。这就是我的工作方式。到目前为止,它运行良好,解决了我的问题。
class Suite < ActiveRecord
...
has_many :furniture, through: :rooms
...
end
suite.furniture # get all pieces of furnishing from all the room in this suite
class Floor < ActiveRecord::Base
has_many :suites
end
class Suite < ActiveRecord::Base
belongs_to :floor
belongs_to :suite_category
has_many :rooms, :dependent => :destroy
end
class SuiteCategory < ActiveRecord::Base
has_many :suites
end
class Room < ActiveRecord::Base
belongs_to :suite
has_and_belongs_to_many :room_types
end
class RoomType < ActiveRecord::Base
has_and_belongs_to_many :rooms
end