2014-11-24 74 views
0

我有一趟模型,每一次旅行的has_many航班,賓館,旅店,CARRENTAL,活動等,每個模式都有自己的領域,但他們都有一個「開始日期」和/或「結束日期」。我想創建一個儀表板並顯示行程。的Rails:檢索多個表中的數據沒有關聯

什麼是查詢數據庫,並有類似的結果,最好的解決辦法:

Row Model Id Date  Type 
#1  Flight 2  2014-12-01 Flight 
#2  Lodging 54 2014-12-02 Check-in 
#3  Lodging 54 2014-12-08 Check-out 
#4  Flight 3  2014-12-10 Flight 

我希望得到這樣的結果,並創建這樣一個行程:

result.each do |itinerary_item| 
    item = @trip.send(itinerary_item.Model).find(itinerary_item.id) 
    ** do things with the item in a view model 
end 

但我的方式我的想法似乎並不聰明。我必須訂購行程日期!

編輯1: 我試圖做這樣的事情:

@trip = Trip.find(1) 
itinerary = {} 
itinerary['items'] = [] 
@trip.flights.each do |flight| 
    itinerary['items'] << [flight.class.name, flight.id, flight.departure_date] 
end 
@trip.lodging.each do |ld| 
    itinerary['items'] << [ld.class.name, ld.id, ld.check_in_date] 
    itinerary['items'] << [ld.class.name, ld.id, ld.check_out_date] 
end 
... and so on with all the related models. and then 
result = itinerary['items'].sort_by {|c, i, date| date } 
... and then 
result.each do |item| 
    ... do the magic querying the database again =(
end 

回答

1

一個非常簡單的方法是在你的Trip模型,返回行程的所有部分添加一個方法。

東西這樣:

def parts 
    (flights + lodgings + rentals + activities).to_a 
end 

,然後在您的視圖遍歷這個parts數組:

@trip.parts.each do |part| 
    # your code here 
end 

UPDATE:

在這種情況下,您可以創建一個包含你想要的每個部分的所有信息的散列:

def parts 
    flights_info = flights.map { |flight| { :model => "Flight", :id => flight.id, :date => flight.date, :type => "flight" } } 
    lodgings_info = lodgings.map { |lodging| { :model => "Lodging, :id => lodging.id, :date => lodging.date, :type => lodging.type } } 
    ... 
    items = (flights_info + lodgings_info + ...).to_a 
    items.sort_by { |item| item[:date] }.reverse 
end 

然後在您的視圖中使用它:@trip.parts.each { |part| part[:model] }。請記住,這是一個讓你感動的非常簡單的方法,你以後肯定需要重新考慮它的體系結構。

+0

你好@sebkomianos!感謝您的回答。但是,我將如何排序部分之間的日期呢?我第一次不清楚,對不起。我編輯了我的問題! – Guido 2014-11-24 15:56:56

+0

@Guido別擔心,我更新了我的答案。 :) – sebkkom 2014-11-24 16:50:53

+0

非常感謝。有關如何「重新思考」這種架構的任何幫助? – Guido 2014-11-24 17:53:59