Time Difference of One Item, Two Fields, Grouped by Days - Rails - ruby-on-rails

Controller
#clock_events = ClockEvent.where(user_id: current_user.id)
#clock_event_days = #clock_events.group_by { |t| t.clock_in.beginning_of_day }
#clock_out = ClockEvent.where(user_id: current_user.id, clock_out: nil).last
View
<% if #clock_events.exists? %>
<div class="row">
<% #clock_event_days.each do |day, clock_events| %>
<div class="col-md-6">
<div class="list-group">
<h4 class="list-group-item-heading"><%= day.strftime("%A, %B #{day.day.ordinalize}") %></h4>
<% clock_events.each do |clock_event| %>
<p class="list-group-item-text time-group">
<%= clock_event.clock_in.strftime("%l:%M%p") %>
<% if clock_event.clock_out.present? %>
-
<%= clock_event.clock_out.strftime("%l:%M%p") %> -
<%= sprintf "%.2f", ((clock_event.clock_out - clock_event.clock_in) / 1.hour) %> hrs
<% end %>
</p>
<% end %>
</div>
<div class="daily-total">
<strong>Total: **need total here**</strong><br>
</div>
</div>
<% end %>
</div>
<% end %>
Result
Friday, February 17th
5:15PM - 6:15PM - 1.00 hrs
5:29PM - 5:41PM - 0.21 hrs
5:49PM - 6:45PM - 0.94 hrs
6:49PM - 6:49PM - 0.00 hrs
6:50PM - 6:57PM - 0.11 hrs
Total:
Saturday, February 18th
4:45PM - 4:52PM - 0.11 hrs
Total:
Can some one help me get the total hours for each day and then for the entire week (Friday-Thursday)?
I am guessing I should be using the model for getting the time difference instead of using the view...but I can't seem to figure it out.

Putting a variable to track this in the view is the most straightforward solution, even if it's maybe not the most elegant one.
<% total_hours = 0 %>
<% clock_events.each do |clock_event| %>
<% total_hours += (clock_event.clock_out - clock_event.clock_in) %>
<% end %>
and then output it
<strong>Total: <%= total_hours / 1.hour %></strong><br>
Edit 1:
You could also clean things up a bit by adding this in the model, something like
class ClockEvent < ApplicationRecord
# ..
def duration
clock_out - clock_in
end
end
and use that in the view
<% total_hours += clock_event.duration %>
...
<%= sprintf "%.2f hrs", (clock_event.duration / 1.hour) %>
Edit 2:
You can clean it up even more by skipping the total_hours variable all together and do this.
<%= clock_events.sum(&:duration) / 1.hour %>

Related

Simple mathematical operation in the view is working in local but not in heroku

I want to puts the result of this simple operation in my pack index view ( pack.quantity / pack.cigs.count).round(1)).
It works fine in local but does not work in heroku. In heroku I can see the result in some packs but not in all the packs.
I don't understand what is happening.
Thanks in advance.
<% #packs.each do |pack| %>
<li class="btn-green">
<%= pack.start_date.strftime("%b %e") %>
<% if pack.end_date %>
<%= pack.end_date.strftime("%b %e") %>
<%= "#{((pack.end_date - pack.start_date) / 60 / 60 / 24).round(1)} days" %>
<% else %>
<strong><%= 'not finished' %></strong>
<%= "#{((Time.zone.now - pack.start_date) / 60 / 60 / 24).round(1)} days" %>
<% end %>
<% if pack.cigs.count > 0 %>
<%= "#{pack.cigs.count} cigs" %>
<%= pack.quantity %>
<% if pack.quantity %>
<%= "#{(pack.quantity / pack.cigs.count).round(1)} g/cigs" %>
<% end %>
<% if pack.price %>
<%= "#{(pack.price / pack.cigs.count).round(1)} €/cigs" %>
<% end %>
<% end %>
Solved problem.
The problem was the operation with two integer with not integer result.
2 / 3 => 0
I've solved with to_f in the operation.
2.t_f / 3 => 0.6666666666
That's all.
Thanks.

How to render only notes that equal date?

Instead of showing all the notes per day, how can we only show one note per day, the note whose note.note_date == date?
Day 1: Notes/notes # Shows both Day 1 and Day 3 note. Only want to show Day 1 note
Day 2: Notes/form
Day 3: Notes/notes # Shows both Day 1 and Day 3 note. Only want to show Day 3 note
Day 4: Notes/form
Day 5: Notes/form
challenges/show
<% #challenge.dates_challenged.first(#challenge.days_challenged).each_with_index do |date, i| %>
Day <%= i + 1 %>
<% if #notes.any? { |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %>
<%= render 'notes/notes' %>
<% else %>
<%= render 'notes/form', :date => date %>
<% end %>
<% end %>
notes/notes
<% #notes.each do |note| %>
<%= note.notes_text %>
<% end %>
notes/form
<%= form_for [#notable, #note] do |f| %>
<%= f.text_area :notes_text, placeholder: 'Enter Recap' %>
<%= f.date_select :notes_date, selected: date, :order => [:month, :day, :year] %>
<% end %>
challenges_controller
def show
#notable = #challenge
#notes = #notable.notes
#note = Note.new
end
To recap, a user creates a challenge. A challenge has the attribute days_challenged. The user chooses how many days will be challenged, i.e. 10, 15, 30, etc. For each of those days a notes/form will be rendered. If a note.notes_date equals a respective day then how can we only show that one note in place of notes/form?
<% if #notes.any?
#today_notes = #notes.select{ |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %>
<%= render 'notes/notes' %>
<% else %>
...
<% end %>
Then use #today_notes in the notes/notes partial.
Change this <%= render 'notes/notes' %> partial to below one, and follow right below note.html.erb file.
Challenges Show:
<%= render partial: 'notes/notes', locals:{note: note} %>
Rename note.html.erb to underscore _notes.html.erb
notes/_notes.html.erb:
<%= note.notes_text %>

Using variable within each function to sort_by

At the moment i'm playing around with Rails to get the hang of it and coding in general. Therefore I created my first rails app in which I want to display my games (from the game database) on one of the pages and sort them by a variable calculated within the each function. My view page looks like this (simplified):
<% #games.sort_by{|game| ???}.each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <% if (game.userexp1 <= 60) %> <%= #UserexpScore = 1 %>
<% elsif (game.userexp1 > 60) %> <%= #UserexpScore = 2 %> = 2 <% end %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <% if (game.price <= 20) %> <%= #PriceScore = 2 %>
<% elsif (game.price > 20) %> <%= #PriceScore = 1 %> <% end %></p>
<p>Finalscore: <%= #FinalScore = #UserexpScore + #PriceScore %></p>
<% end %>
I get how i can order them by game.userexp1 or game.price but I can't figure out if it is possible to sort them by #FinalScore (without also putting the userexpscore and pricescore in the database). I was wondering if this is possible and if yes how I can do that.
Thanks in advance!
View is not proper place for business logic.
You can move score calculating logic into model, e.g.:
class Game < ActiveRecord::Base
def userexp_score
userexp1 <= 60 ? 1 : 2
end
def price_score
price <= 20 ? 2 : 1
end
def final_score
userexp_score + price_score
end
end
Then in view
<% #games.sort_by(&:final_score).each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <%= game.userexp_score %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <%= game.price_score %></p>
<p>Finalscore: <%= game.final_score %></p>
<% end %>
I suggest you read about MVC and separation of concerns

Time on Rails baseball schedule app off by 5 hours on production

I have an app: http://arethebaronsplaying.com/ that breaks everyday at 7pm US Central time on production, but works correctly locally. The site is hosted by Ninefold.
In short, I have a seeds.rb file with a bunch of Game objects, and one of the attributes for a Game is date, which is set to the m/d format, ex. 4/09.
And every day at 7pm the app breaks by displaying a big NO and text saying when the next game is, and the next game is the current day's game. Then below that, it will display a YES! with the current day's game.
So it's displaying a YES and a NO, which makes me think that perhaps Date.today is calculating time differently than Time.now, and since I'm using both of them, the one that is wrong will display the NO.
Anyway, here's my logic:
<% i = 0 %>
<% games.each do |game| %>
<% if game.date.strftime("%_m/%d")[1..-1] == Time.now.strftime("%_m/%d")[1..-1] && game.away == false %>
<h1 class="main-text answer yesanswer" id="responsive_headline"><%=link_to "YES!", "http://www.milb.com/tickets/singlegame.jsp?sid=t247", target: "_blank" %></h1>
<% i = 1 %>
<br>
<h2 class="main-text2 gamewrap" id="responsive_headline2">
<% if game.away == false %>
<span class="next-venue">vs.</span>
<span class="next-opponent"><%= game.opponent %></span> |
<span class="next-time"><%= game.time %></span>
<% else %>
<span class="next-venue">at</span>
<span class="next-opponent"><%= game.opponent %></span> |
<span class="next-time"><%= game.time %></span>
<% end %>
</h2>
<% elsif game.date.strftime("%_m/%d")[1..-1] == Time.now.strftime("%_m/%d")[1..-1] && game.away == true %>
<% unless i == 1 %>
<a><h1 class="main-text answer" data-reveal-id="myModal" data-reveal id="responsive_headline">NO.</h1></a>
<% i = 1 %>
<h2 class="main-text2 gamewrap" id="responsive_headline2">
<span class="next-venue">away game</span>
<span class="next-opponent">#<%= game.opponent %></span>
</h2>
<% end %>
<% else %>
<% unless i == 1 %>
<a><h1 class="main-text answer" data-reveal-id="myModal" data-reveal id="responsive_headline">NO.</h1></a>
<% i = 1 %>
<h2 class="main-text2 gamewrap" id="responsive_headline2">
<span class="next-venue">vs.</span>
<span class="next-opponent">
<% if next_home_game > 1 %>
<%= game.opponent %>
in <%= next_home_game %> days |
<% else %>
<%= game.opponent %>
in <%= next_home_game %> day |
<% end %>
<span class="next-time"><%= game.time %></span>
</h2>
<% end %>
<% end %>
<% end %>
I've tried adding config.time_zone = 'Central Time (US & Canada)' to both application.rb and production.rb and it broke the deployment.
Here's how Ninefold does Time: https://help.ninefold.com/hc/en-us/articles/201320124-What-time-standard-does-Ninefold-use-
Thanks for your help!
Dates and times (across timezones) are a nightmare to manage (I know that's not much help... but I've been there and you have my condolences).
Anyway... try replacing all of your Time.now and Date.today calls with Time.zone.now and Time.zone.today respectively.
Ensure all of your times are stored in the DB in UTC (no matter what your local time, or the server's time) and check out some articles that give other advice (like http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails and http://danilenko.org/2012/7/6/rails_timezones/)
Good luck!

Order by time_field

I have a database table called "bookings" which users can select the 'time_from' and 'time_to' in which they want the booking done.
When adding these fields to the database I added them as a time_field.
<%= f.label :time_from, "From (24hr Clock)" %>
<%= f.time_field :time_from %>
<%= f.label :time_to, "To (24hr Clock)" %>
<%= f.time_field :time_to %>
The form works and saves correctly but my problem is the order. Below is my controller code and subsequently my view to display the time and its output. Any idea on how to order these by time correctly?
Controller:
def show
#location = Location.find(params[:id])
#booking = Booking.order("time_to")
#company = Company.all
end
View:
<% 0.upto(11.to_i).each do |day_count| %>
<span class="col-md-3 booking-times">
<h4><%= time_tag(Date.today + day_count.days) %></h4>
<span class="label label-danger no-bookings">No Bookings</span>
<% #booking.each do |b| %>
<% if b.date == Date.today + day_count.days && b.type == "Meeting" %>
<% if b.location == params[:id] %>
<span class="label label-info booking-time">
<%= time_tag(b.time_from, :format=>"%H:%M") %> -
<%= time_tag(b.time_to, :format=>"%H:%M") %>
</span>
<% #company.each do |c| %>
<% if c.id == b.company %>
<%=link_to c.name, c %></br>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</span>
<% end %>
Output: (For first day time)
09:30 - 10:30
22:00 - 23:00
07:30 - 08:30
I appreciate this is not the nicest looking code. I would like the above output to order by time. Any ideas? I have tried to order in the controller, this effects the layout but not in the correct order still. I think the dat attatched to the time_to input may be having ian affect? Thanks!
Have you tried this:
#booking = Booking.order(time_to: :desc)
Can you please try this:
#booking = Booking.order('time_to desc')

Resources