简体   繁体   English

设置 Has_Many:through 关联

[英]Setting up a Has_Many :through Association

On the application I'm currently working on, I'm stuck on setting up the associations between 3 models to ensure referential integrity.在我目前正在处理的应用程序上,我坚持设置 3 个模型之间的关联以确保引用完整性。 I have an Event model, Building model, and a Room model.我有一个活动 model、建筑 model 和一个房间 model。 The association in real life is pretty intuitive.现实生活中的关联非常直观。 An Event can only be in one Building and one Room.一个事件只能在一个建筑物和一个房间中。 A Building clearly can have multiple rooms.一个建筑物显然可以有多个房间。

Here's what I have set up now.这是我现在设置的。 However, how can Events specify their room if they belong to Buildings, and the foreign key for the Room is in the Events table?但是,如果 Event 属于 Buildings,并且 Room 的外键在 Events 表中,Events 如何指定它们的房间? Is this where you use a has_many:through relationship?这是您使用 has_many:through 关系的地方吗? Is it good practice to store both the Building and Room foreign keys in the Event table, as Rooms are owned by Buildings?将 Building 和 Room 外键存储在 Event 表中是否是一种好习惯,因为 Room 由 Buildings 拥有? What about the conditional relationship that requires a building to be specified before allowing a room to be specified (some buildings have 2 rooms, others have 20, for example)在允许指定房间之前需要指定建筑物的条件关系怎么样(例如,有些建筑物有 2 个房间,有些有 20 个房间)

Sorry I'm so unclear on this.抱歉,我对此不清楚。 Thanks in advance for the help!在此先感谢您的帮助!

    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

I would recommend the following:我会推荐以下内容:

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

This way you can do @room.events , @event.building , @building.events这样你就可以做到@room.events@event.building@building.events

I think the best way to handle this is to do something like the following:我认为处理此问题的最佳方法是执行以下操作:

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

So you can use has_one:through to specify that an event owns a hotel所以你可以使用 has_one:through 来指定一个事件拥有一家酒店

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM