this might bit of basic question, searched , wasn't able find answer.
in rails app, show random joke on page whenever page loads. i'd implement 'joke of day', same joke displays day , refreshes each day @ midnight. can point me in right direction?
here's code i'm using display random joke:
class jokescontroller < applicationcontroller def index @joke = joke.limit(5).order("random()").last end end
and view:
<div class="col-sm-10 saying"> <%= @joke.saying.html_safe %> </div>
thanks in advance!
a better solution came later
controller
class jokescontroller < applicationcontroller def index @joke = joke.joke_of_the_day end end
model
class joke < activerecord::base def self.joke_of_the_day joke = joke.where(joke_of_the_day: date.today).first # joke picked if joke.present? joke # pick joke today else joke = joke.order("random()").first joke.update(joke_of_the_day: date.today) joke end end end
don't forget add joke_of_the_day
field jokes table type date
my original answer
this not perfect solution, algorithm can improved:
def joke_of_the_day count = joke.count # make sure joke unique of particular # date. can more complexe calculation make sure it's # unique basic idea sum_of_date = date.today.year + date.today.month + date.today.day # loop make sure sum_of_date not greater count of jokes new_count = loop if sum_of_date >= count sum_of_date = sum_of_date / 2 else break (count - sum_of_date) end end joke.first(new_count).last end
Comments
Post a Comment