每隔24小时从我的链接表中获取一个随机链接

时间:2016-01-06 17:13:28

标签: ruby-on-rails ruby

我的数据库中有一个链接表,我正在尝试在我的应用上创建一个名为'当天链接的页面。

我想要做的是每隔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 %>

任何人都可以带领我朝着正确的方向前进吗?

1 个答案:

答案 0 :(得分:3)

有几件事:

1)除非您使用react.rb之类的内容,否则链接不会动态更新。但是你说24小时,所以我假设你只是希望如果用户第二天访问你的网站,他们会看到不同的链接。没关系。

2)对于测试,您只需刷新页面,它在前30秒内应该看起来相同,然后在30秒后如果再次刷新它将会改变。

3)您想将所有逻辑移动到控制器和模型。您将需要使用rails缓存来存储您随机选择的链接,然后在&#34; timeout&#34;中使缓存值到期。时间(1天,30秒,无论如何)。幸运的是,这在铁轨上很容易。

4)如果你真的想确保链接永远不再显示(至少在显示所有其他链接之前),你必须在模型中添加一个计数器

具体而言(向后工作)

将属性display_count添加到Link模型。确保它是一个初始化为零(不是零)的整数值

向模型添加方法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