[英]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.