从我的链接表随机链接每24小时一次

从我的链接表随机链接每24小时一次

问题描述:

我有我的数据库链接的表,我试图让我的应用程序被称为“一天的链接”的页面。从我的链接表随机链接每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

请勿将该代码放入您的视图中。在控制器中执行。 –

几件事情:

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),看看发生了什么。 –