在我目前正在开发的应用程序中,我一直在设置3个模型之间的关联,以确保引用完整性。我有一个事件模型、一个建筑模型和一个房间模型。现实生活中的联想是相当直观的。一个活动只能在一座大楼和一个房间中进行。一座建筑物显然可以有多个房间。
这是我现在设置的内容。但是,如果事件属于建筑物,并且房间的外键在Events表中,那么事件如何指定它们的房间?这就是你使用has_many :直通关系的地方吗?在事件表中同时存储Building和Room外键是不是一种好的做法,因为房间是由建筑物拥有的?在允许指定房间之前需要指定建筑物的条件关系如何(例如,一些建筑物有2个房间,其他建筑物有20个房间)
对不起,我不太清楚这一点。提前感谢您的帮助!
class Event < ActiveRecord::Base
belongs_to :building
end
class Building < ActiveRecord::Base
has_many :events
has_many :rooms
end
class Room < ActiveRecord::Base
belongs_to :building
end发布于 2011-04-30 16:06:37
我认为处理这个问题的最好方法是这样做:
class Event < ActiveRecord::Base
belongs_to :room
has_one :building, :through => :room
end
class Building < ActiveRecord::Base
has_many :events
has_many :rooms
end
class Room < ActiveRecord::Base
belongs_to :building
end因此,您可以使用has_one :through来指定事件拥有一家酒店
发布于 2017-04-19 21:12:42
我会推荐以下几点:
class Event < ActiveRecord::Base
belongs_to :room
has_one :building, through: :room
end
class Building < ActiveRecord::Base
has_many :events, through: :rooms
has_many :rooms
end
class Room < ActiveRecord::Base
belongs_to :building
has_many :events
end这样你就可以做@room.events、@event.building、@building.events
https://stackoverflow.com/questions/5840343
复制相似问题