Ruby on Rails - show only current date

I am creating a small lesson application with a different lesson for every day. I want to show the current lesson only by index and cannot figure out how to do this. I googled and found some information that came close but still could not solve the problem. I have only one controller, DaysController. There is no user controller.

For my model (day.rb) I tried this

class Day < ActiveRecord::Base
  validates :description, :date, :link_to, :presence => true
  scope :created_on, lambda {|date| {:conditions => ['created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day]}}


  def self.today
    self.created_on(Date.today)
  end

end

And for my index, I tried these

  <% @day.created_on(Date.today) %>

  <% @day.today %>

any advice

+4
source share
3 answers

If I understand correctly and for simplicity, is this basically what you are trying to achieve?

Controller:

def index
 @days = Day.all
end

View (index.html.erb):

<% @days.each do |day| %>
<% if day.created_at == Date.today %>
 <%= day.field_name %>
<% end %>
+1
source

scope, Date, , , :

scope :created_on, ->(date) { where(created_at: date) }

Day.today - .

+1

You can do the following:

class Day < ActiveRecord::Base
  scope :today, lambda { where('CAST(created_at AS date) = ?', Date.today) }

And use it as follows:

@days = Day.today
# returns a list of `Day` records where the `created_at` date is equal to today date
+1
source

Source: https://habr.com/ru/post/1606860/


All Articles