我正在以一种特定的方式创建一个类似于臭名昭著的 Woot 的网站:我想以每天一个的速度轮换产品。我正在使用 RoR,并且更愿意动态选择一种产品,而不必每天输入一个。所以这里是要求:
1) 每天获取一个新产品
2) 从表中动态选择
3) 确保不要两次选择相同的产品
就是这样。在产品表中,我目前有一个名为 listed
的 bool 值,它将标记产品是否已列出。我的问题是,我是否应该运行某种数据库作业来选择当天的产品,或者我是否可以通过某种方式对日期进行哈希处理并得出一个应用程序将在日期更改之前显示的 ID。
感谢抽空。
最佳答案
就个人而言,我会保持简单并按照预定的工作方法进行。更具体地说,我可能会使用 whenever gem 来包装每天午夜运行一次的 cron-job。然后,您可以在 Product
模型中设置一个方法来选择当前的“今日产品”。
像这样的东西应该可以工作:
product.rb
class Product < ActiveRecord::Base
# Return the current product of the day
def self.product_of_the_day
where(listed: true).first
end
# Set up the product of the day
def self.setup_product_of_the_day
current_product = self.product_of_the_day
product_ids = where.not(id: current_product.id).pluck(:id)
next_product = self.find(product_ids.sample)
current_product.update_attribute(:listed, false)
next_product.update_attribute(:listed, true)
end
end
schedule.rb
every 1.day do
runner "Product.setup_product_of_the_day"
end
关于ruby-on-rails - Rails 中的每日轮换产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397811/