开发者

Rotating product of the day in Rails

开发者 https://www.devze.com 2022-12-22 17:19 出处:网络
I am creating a site similar to the infamous Woot in one particular way:I would like to rotate through products at a rate of one per day.I am using RoR, and would prefer to dynamically choose a produc

I am creating a site similar to the infamous Woot in one particular way: I would like to rotate through products at a rate of one per day. I am using RoR, and would prefer to dynamically choose a product, and not have to enter one each day. So here are the requirements:

1) Get a new product each day

2) Select dynamically from a table

3) Make sure not to select the same product twice

Thats about it. In the products table, I currently have a boolean called listed which will mark if the product has been listed. My question is, should I run some kind of database job to choose a product for that day or is there some way I can like hash th开发者_C百科e date and come up with an id that the app will display until the date changes.

Thanks for the time.


Personally, I would keep it simple and go the scheduled job approach. To be more specific, I'd probably use the whenever gem to wrap a cron-job that runs once daily at midnight. You can then set up a method in your Product model to select the current 'Product of the Day'.

Something like this should work:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消