我有一個用戶表下面的模式:Ruby on Rails的數據建模
User -- id , name , age etc
和騎表下面的模式:
Ride -- id , from , to etc.
我也有一個預訂表格:
Booking - id, User_id, Ride_id
有沒有什麼方法可以描述像from , to etc
這樣的騎行的細節,以及關於預訂的用戶的詳細信息?
我有一個用戶表下面的模式:Ruby on Rails的數據建模
User -- id , name , age etc
和騎表下面的模式:
Ride -- id , from , to etc.
我也有一個預訂表格:
Booking - id, User_id, Ride_id
有沒有什麼方法可以描述像from , to etc
這樣的騎行的細節,以及關於預訂的用戶的詳細信息?
假設你有如下關係:
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
創建模型用戶,騎乘和預訂。那麼你可以使用booking.ride.from
,user.bookings.last.ride.to
。這一切都在這裏解釋http://guides.rubyonrails.org/association_basics.html。