繁体   English   中英

设置 Has_Many:through 关联

[英]Setting up a Has_Many :through Association

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

这是我现在设置的。 但是,如果 Event 属于 Buildings,并且 Room 的外键在 Events 表中,Events 如何指定它们的房间? 这是您使用 has_many:through 关系的地方吗? 将 Building 和 Room 外键存储在 Event 表中是否是一种好习惯,因为 Room 由 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

我会推荐以下内容:

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

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

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

暂无
暂无

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

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