[英]has_many ,through association Rails
您好,我需要帮助来为数据库创建结构(PostgreSQL)
我想创建一个集合(查询),它可以获取建筑物特定单位的所有房间。
biulding.find(1).flats.find(1).rooms.
我该如何组织我的关联以将其存档?
谢谢
这是模型
class Building < ApplicationRecord
has_many :flats
has_many :rooms, through: :flat
end
class Flat < ApplicationRecord
belongs_to :building
has_many :rooms
end
class Room < ApplicationRecord
belongs_to :flat
belongs_to :building
end
create_table "buildings", force: :cascade do |t|
t.string "name"
.....
end
------------------
create_table "flats", force: :cascade do |t|
t.string "number"
t.bigint "building_id"
t.bigint "room_id"
t.index ["building_id"], name: "index_flats_on_building_id"
t.index ["room_id"], name: "index_flats_on_room_id"
end
-------------------------------
create_table "rooms", force: :cascade do |t|
t.string "number"
t.bigint "flat_id"
t.bigint "building_id"
t.index ["building_id"], name: "index_rooms_on_building_id"
t.index ["flat_id"], name: "index_rooms_on_flat_id"
end
出发点是什么? 如果您有单位,则可以执行flat.rooms
或Room.where(flat: flat)
或Room.where(flat_id: id)
。 如果您有建筑物,则如果您具有has_many :rooms, through: :flats
Building.find(1).rooms
则可以执行Building.find(1).rooms
。
您的协会可以按您的要求做。
如果要获取给定单位的房间,可以执行以下操作: Flat.find(id).rooms
或flat.rooms
如果您已经设置了一个名为flat的变量)。
编辑:由于声誉限制,我无法回复评论,所以我在这里回复。
谢谢。 另一个问题。 我如何查询以了解建筑物中的房间和单位数量
您可以通过在请求中添加.count
方法来实现。 像flat.rooms.count
或building.flats.count
。
协会似乎是用于将房间平铺到房间,反之亦然。
集合查询,它将列出与特定建筑物和特定公寓相对应的所有数据:
Building.where(id: 1).joins(:flats).first.rooms.where("flats.flat_id = ?",1)
希望能帮助到你!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.