foliwe83
foliwe83

Reputation: 590

has_many ,through association Rails

Hello I need help to create a structure for my database (PostgreSQL)

I want to create a collection(query) that can get all the rooms of a particular flat of a building .eg.

biulding.find(1).flats.find(1).rooms.

How can I structure my association to archive that?

Thanks

Here are the models

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

schema

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

Upvotes: 0

Views: 66

Answers (3)

carrion crow
carrion crow

Reputation: 26

Your associations are fine to do what you're asking.
If you want to get rooms for a given flat, you can do : Flat.find(id).rooms or flat.rooms if you've already set a variable named flat.

edit: I can't reply to comment due to reputation limitation, so I reply here.

Thanks. Another question. How can I query to know the number of rooms and flats in the building

You can do that by adding the .count method to your request. Like flat.rooms.count or building.flats.count.

Upvotes: 1

Rohan
Rohan

Reputation: 2727

Association seems fine whether it is for building to flat to rooms and vice versa.

Collection Query, it would list all the data corresponding to a particular building and particular flat:

Building.where(id: 1).joins(:flats).first.rooms.where("flats.flat_id = ?",1)

Hope it helps!!

Upvotes: 0

Daryll Santos
Daryll Santos

Reputation: 2081

What's the starting point? If you have the flat, you can do flat.rooms or Room.where(flat: flat) or Room.where(flat_id: id). If you have the building, you can do Building.find(1).rooms if you have a has_many :rooms, through: :flats.

Upvotes: 1

Related Questions