设置Has_Many:通过关联

时间:2011-04-30 07:36:02

标签: ruby-on-rails ruby associations model-associations

在我目前正在开发的应用程序上,我坚持设置3个模型之间的关联以确保参照完整性。我有一个事件模型,建筑模型和房间模型。现实生活中的联想非常直观。活动只能在一个建筑物和一个房间内。建筑显然可以有多个房间。

这是我现在设置的内容。但是,如果事件属于建筑物,事件如何指定它们的房间,并且房间的外键位于事件表中?这是你使用has_many:through关系的地方吗?将Building和Room外键存储在Event表中是不错的做法,因为Rooms属于Buildings?在允许指定房间之前要求建筑物指定的条件关系怎么样(例如,一些建筑物有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

2 个答案:

答案 0 :(得分:1)

我认为处理此问题的最佳方法是执行以下操作:

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来指定事件拥有酒店

答案 1 :(得分:1)

我会推荐以下内容:

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

相关问题