2016-01-06 77 views
0

我有我的數據庫鏈接的表,我試圖讓我的應用程序被稱爲「一天的鏈接」的頁面。從我的鏈接表隨機鏈接每24小時一次

我想要做的是每24小時從我的鏈接表中獲取一次隨機鏈接(爲了測試目的,每30秒左右一次),然後確保每24小時選取的每個值都不會被選中再次。

links_controller.rb:

def quote_of_the_day 
    @links = Link.all 
    end 

quote_of_the_day.html.erb:

什麼,我想在這裏說,每30秒,給我從我的links_array隨機鏈接。

<% @links_array = @links.to_a %> 
<% @time = Time.now %> 
<% @time_plus_30 = @time + 30 %> 

<% when @time_plus_30 %> 
    <%= @links_array.try(:sample) %> 
<% end %> 

任何人都可以引導我什麼,我想在這裏做了正確的方向?

+2

你「等於」運算符是錯誤的。您需要使用「=」而不是比較運算符「==」。 – archana

+0

請勿將該代碼放入您的視圖中。在控制器中執行。 –

回答

3

幾件事情:

1)除非你使用類似react.rb鏈接將不會動態更新。但是你說24小時,所以我想你只是希望如果用戶第二天訪問你的網站,他們會看到不同的鏈接。沒關係。

2)進行測試,你將不得不只刷新頁面,它應該同爲前30秒,最後30秒後,如果你再次刷新它會改變。

3)你想所有的邏輯移至控制器和模型。您需要使用rails緩存來存儲您隨機選擇的鏈接,然後在「超時」時間(1天,30秒,無論)中過期緩存值。幸運的是,這在軌道上很容易。

4)如果你真的想確保一個鏈接是永遠不會再次顯示(至少要等到所有其他環節已經顯示),你將有一個計數器添加到模型

那麼具體的(向後工作)

添加屬性display_countLink模型。確保它被初始化爲零的整數值(不爲零)。

添加的方法get_new_url到模型。它看起來像這樣

def self.get_new_url 
    # get the minimum value of display_count from the db 
    min_count = minimum(:display_count) 
    # build a query to get all the links with same count 
    min_links = where(display_count: min_count) 
    # pick a random offset by counting the links with the same count 
    random_link_offset = rand(0..min_links.count-1) 
    # select the link that is at that offset 
    link = min_links.limit(1).offset(random_link_offset).first 
    # don't forget to update its count and save it 
    link.display_count += 1 
    link.save 
    link 
end 

最後在你的控制器,你會做到這一點

def get_link 
    Rails.cache.fetch("current_random_link", expires_in: 24.hours) do 
     Link.get_new_url # will only be called every 24 hours when the cache expires 
    end 
    end 
+0

只是一個筆記 - 學習使用所有rails和ruby測試善良的好機會。你可以在模型中爲上述方法構建非常好的測試用例,如果你想要控制器(儘管模型正在做所有的努力,所以我會專注於測試) –

+0

感謝這個答案,米奇。 目前我有高速緩衝存儲器組控制器10.seconds'後'到期,我設置'@link = Link.get_new_url'。 然後,我在我的視圖中調用@link來查看是​​否會將對象返回,但我一直無法檢索該對象。 我跑了一個遷移,在我的鏈接表中包含'display_count',並將默認值設置爲0. 然後我用'Link.update_all「display_count = 0」'更新了所有當前鏈接。 鏈接仍然沒有通過。你看到我做過的錯誤嗎? – Jbur43

+0

運行一個'rails console',然後你可以在那裏玩(即做一個Link.get_new_url),看看發生了什麼。 –