2013-01-14 143 views
0

我有3個模型:運營商,產品,費率。每個承運人has_many :products和每個產品has_many :rates。我正在嘗試創建一個html表格,該表格將循環顯示每個產品,並僅顯示最新的費率。我假設我需要將它存儲在一個數組(或散列?)中,但不太清楚如何(因爲我是編程新手,但學習!)。有人可以幫忙嗎?如何從多個表創建陣列

回答

0

我會做模型是這樣的:

class Product < ActiveRecord::Base 
    def current_rate 
    rates.order('created_at ASC').last 
    end 
end 

然後這個視圖:

<%= product.current_rate %> 
+0

簡單而有效的..非常感謝你! –

1

最近的匯率是在您的數據庫上創建的最後匯率。如果這個信息是真的,那意味着只有一個(limit 1)行按創建日期降序(created_at DESC)排序的SQL查詢將獲得您想要的記錄。知道了這一點,你可以在你的速度模型創建範圍:

scope :current_rate, order('rates.created_at DESC').limit(1).first 
# As @AntohnyAlberto said, limit would bring an array, so you may use .first on the results 
# Or you can use just .first, as it would bring only the first one 
scope :current_rate, order('rates.created_at DESC').first 

並在您的視圖中使用此範圍在您的產品循環:

<%= product.rate.current_rate %> 
+0

使用'limit',AR將帶回一組模型...更好地使用'first'來直接取回對象:'scope:current_rate,order('rates.created_at DESC')。' –

+0

@AnthonyAlberto噢,更新答案。 – MurifoX

+0

謝謝..我會試試這個 –