Remco
Remco

Reputation: 683

How to define my DB relationships

We have the following (part) models.

User
Booking
Apartment
Villa
Bed_Breakfast
Boutique_hotel

The user can have many bookings and a booking can have many villas, apartments, B&B or boutique hotels.

This is my idea to set up the relationships.

class User 
 has_many: bookings
end

class booking
 belons_to :user
end

class Apartment
 belongs_to :booking
end

class Villa
 belongs_to :booking
end

Is this the right way to do it?

Thanks...

remco

Upvotes: 0

Views: 52

Answers (3)

Rails Guy
Rails Guy

Reputation: 3866

I think, your approach is not good. Seems you are looking for has_many :through association in your tables. you can have a look into Rails has_many :through Docs. you should go like this:

class User 
 has_many :apartments, through: bookings
end

class booking
 belongs_to :user
 belongs_to :apartment
end

class Apartment
 belongs_to :user
 has_one :booking
end

Hope it will help. Thanks.

Upvotes: 1

Robbie Guilfoyle
Robbie Guilfoyle

Reputation: 3421

Villa and Apartment seem to be the same thing. Are they not both a Property? You could have a Property to keep yourself DRY (don't repeat yourself) which would eliminate writing the same code for each of the Apartments/Villas. My recommendation is this:

class Villa < Property < ActiveRecord::Base
end 

class Apartment < Property < ActiveRecord::Base
end

Alternatively you could use a Polymorphic Design and have a property type.

Upvotes: 0

techvineet
techvineet

Reputation: 5111

Yeah everything looks good and add this

class booking
 belongs_to :user
 has_many :villas
 has_many :apartments
 ...
end

Upvotes: 0

Related Questions