0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.