"The daylight on the website"
-
I'm building a "Director of Day" in ruby on rails. We need to get the tape off in a random way and not change in one day.
You can make an accidental recipe:
@recipe_day = Recipe.order("RANDOM()").first
But with every reboot of the page, naturally, it will come out differently. How do you make sure he doesn't change all day?
-
Add the field to through migration:
rails g migration AddTopToRecipes top:boolean
To avoid three conditions (true, false, nil) it is better to:
add_top_to_recipes.rb
class AddTopToRecipes < ActiveRecord::Migration def change add_column :recipes, :top, :boolean, null: false, default: false end end
Don't forget to migration:
rake db:migrate
recipe.rb
class Recipe < ActiveRecord::Base # Return the current recipe of the day def self.recipe_of_the_day self.find_by_top(true) end
Set up the recipe of the day
def self.setup_recipe_of_the_day
current_recipe = self.recipe_of_the_dayrecipe_ids = self.all( :select => "id", :conditions => ['id != ?', current_recipe.id] ) next_recipe = self.find(recipe_ids[rand(recipe_ids.length)]) current_recipe.update_attribute(:top, false) next_recipe.update_attribute(:top, true)
end
end
Use the recipe once a day. http://github.com/javan/whenever ♪
Set the target on the schedule:schedule.rb
every 1.day do
runner "Recipe.setup_recipe_of_the_day"
end
ps: The code is better re-established.