2013-02-13 118 views
0

我有一個用戶表下面的模式:Ruby on Rails的數據建模

User -- id , name , age etc

和騎表下面的模式:

Ride -- id , from , to etc.

我也有一個預訂表格:
Booking - id, User_id, Ride_id

有沒有什麼方法可以描述像from , to etc這樣的騎行的細節,以及關於預訂的用戶的詳細信息?

回答

2

假設你有如下關係:

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 

你可以檢索你想要的任何信息。

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

此外,:through可以讓你直接從ride,反之亦然訪問user

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