Girish Koundinya
Girish Koundinya

Reputation: 133

Ruby on Rails Data Modeling

I have a User table with the following schema:

User -- id , name , age etc

and a Ride table with the following schema:

Ride -- id , from , to etc.

I also have a Bookings table with the schema:
Booking - id, User_id, Ride_id

Is there any way I can describe the details about the ride like from , to etc and also details about the user who made the booking?

Upvotes: 0

Views: 1061

Answers (2)

gabrielhilal
gabrielhilal

Reputation: 10769

Assuming that you have the following relationship:

class User < ActiveRecord::Base
  has_many :bookings
  has_many :rides, :through => :bookings
end

class Booking < ActiveRecord::Base
  belongs_to :user
  belongs_to :ride
end

class Ride < ActiveRecord::Base
  has_many :bookings
  has_many :users, :through => :bookings
end

You can retrieve any information you want.

booking = Booking.find(1)
booking.user.name
=> #return user name
booking.ride.from
=> #return ride from
etc

Furthermore, the :through allows you to access the user directly from ride and vice-versa:

user = User.find(1)
user.rides
=> #return all rides for that user

Upvotes: 2

Alex Teut
Alex Teut

Reputation: 844

Create models User, Ride and Booking. Then you can use booking.ride.from, user.bookings.last.ride.to. This all is explained here http://guides.rubyonrails.org/association_basics.html.

Upvotes: 0

Related Questions