Rails get date to variable - ruby-on-rails

I would like to make something like show posts from a particular date.
I have
<% date =Date.parse('2014-06-18') %>
<% if feed_item_users.created_at < (date+1).strftime('%Y-%m-%d') && feed_item_users.created_at > date %>
<li id="<%= feed_item_users.id %>">
<span class="content"><%= wrap(feed_item_users.content) %></span>
<span class="timestamp">
Published: <%= I18n.l feed_item_users.created_at, :format => :h %>
</span>
</li>
<% end %>
in my view I'm checking date.
Now I would like to make a date_time select to get date from my web in format like '2014-06-18' and make default today date.
I know that it should look like that:
<%= form_for(??????) do |f| %>
<div class="field">
<%= f.label :published_at %><br>
<%= f.datetime_select :published_at %>
</div>
<% end %>
but I don't know how to make it to variable because I need it only one time.

You're comparing dates against strings here which isn't reliable. In your ruby code you should always compare dates against dates (or times).
Your logic seems to be "if created at is greater than the start of today and less than the start of tomorrow", which can be massively simplified to "if it's today".
ie you can replace this
<% date =Date.parse('2014-06-18') %>
<% if feed_item_users.created_at < (date+1).strftime('%Y-%m-%d') && feed_item_users.created_at > date %>
with this
<% if feed_item_users.created_at.to_date == Date.today %>
The datetime_select is documented here
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html

strftime returns string so when you apply less then operator it doesn't work.
Better way is to do it like this:
time = Time.new(2014, 06, 18)
if feed_item_users.created_at > time.at_beginning_of_day && feed_item_users.created_at < (time+1.day).at_beginning_of_day

Related

comparison of ActiveSupport::TimeWithZone with 12 failed

I have restaurants where user can make reservations. For reservations, I set my time attribute as integer. I then used a helper to display time selection(radio button) such as 14 to 2:00pm.
def new_time(h)
if h > 12
(h-12).to_s + ":00 PM"
elsif h == 12
h.to_s + ":00 PM"
else
h.to_s + ":00 AM"
end
end
Reservation time options are displayed on Restaurant page:
<%= form_for([#restaurant, #reservation], :html => {:class => 'reserve-form'}) do |f| %>
<div class="times">
<% #restaurant.hours_open.each do |h| %>
<%= f.radio_button :time, h %>
<%= f.label "time_#{h}", new_time(h), class: "reserve" %>
<% end %>
</div>
<div class="align">
<%= f.label :party_size,'Please enter party size' %>
<%= f.text_field :party_size %>
</div>
<div class="align">
<%= f.submit %>
</div>
Now when reservation is done, I redirect to User Profile to display that reservation. Everything works fine on development side but after deploying to heroku, I get error "We're sorry, but something went wrong." when making a reservation and I think it has something to do with reservation time displayed on user page shown below.
When I check heroku logs this is the error:
ActionView::Template::Error (comparison of ActiveSupport::TimeWithZone with 12 failed):
<% #user.reservations.each do |reservation| %>
<div class="user-reservation align">
<p>Restaurant: <%= reservation.restaurant.name %></p>
<p>Reserved Time: <%= new_time(reservation.time) %></p>
<p>Party Size: <%= reservation.party_size %></p>
<p>Added on: <%= reservation.created_at.strftime("%B %d, %Y") %></p>
app/helpers/application_helper.rb:3:in `>'
app/helpers/application_helper.rb:3:in `new_time'
app/views/users/show.html.erb:19:in `block in _app_views_users_show_html_erb__1649677434053595894_70057403913200'
app/views/users/show.html.erb:16:in `_app_views_users_show_html_erb__1649677434053595894_70057403913200'
You are comparing the attribute reservation.time which is a ActiveSupport::TimeWithZone with an integer.
If your datatype is a time, why don't use just format it with strftime ?
<p>Reserved Time: <%= reservation.time.strftime("%I:%M%p") %></p>

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')

A custom validation for checkbox_box_tag

Ok, I have this in my _form.html.erb
<div class "field">
<%= label_tag "What days of the week do you want to work with us? (maximum of three days)" %>
<span>What days of the week do you want to work with us? (maximum of three days)</span><br />
<%= check_box_tag 'days_of_week[]', "Monday" %> Monday
<%= check_box_tag 'days_of_week[]', "Tuesday" %> Tuesday
<%= check_box_tag 'days_of_week[]', "Wednesday" %> Wednesday
<%= check_box_tag 'days_of_week[]', "Thursday" %> Thursday
<%= check_box_tag 'days_of_week[]', "Friday" %> Friday
<%= check_box_tag 'days_of_week[]', "Saturday" %> Saturday
<%= check_box_tag 'days_of_week[]', "Sunday" %> Sunday
</div>
How do I write a custom validation for it to ensure that a person does check three or less?
Here's a little background that complicates it a bit .. look at the code below, see #new_partnership? it's not part of that ... it does show up in parameters, but not in :new_partnership parameters.
just wanted to explain that.
<%= form_for(#new_partnership) do |f| %>
<% if #new_partnership.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#new_partnership.errors.count, "error") %> prohibited this new_partnership from being saved:</h2>
<ul>
<% #new_partnership.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Please let me know if there is additional info should I have to give.
EDIT 1
Also, before anyone suggests jQuery, etc ... is there a way to validate this just in ROR without having to resort to it?
You know, something like this:
validates :days_of_week, :presence => { :message => "Must check three or less" }
two problems from the statement above, one is that ROR says that days_of_week is undefined method (obviously since it's a custom tag) and secondly, it doesn't actually check to see if 3 or less checkboxes were checked.
You can always construct free-form validators with validates_each:
validates_each :days_of_week do |record, attr, value|
record.errors.add attr, ' must have 3 or fewer checked.' if value.length > 3;
end
Note that for this to work your model must be able to use an array-valued attribute, which probably requires specialized accessors.
What you wrote in the "background" part of your question doesn't signify anything as far as I can see.

Having trouble parsing and spacing date/fixnum objects

I'm building a small app that takes things entered into an input field and displays them directly below that input field when entered.
My goal with this code is to separate those entries by date so that all things posted on June 1 are posted with one line break between them and the first entry of June 2 has 2 spaces between it and the entries from June 1.
This is my code and it's not acting as planned but I can't figure out why, I think it stems from line 3 and something I'm doing incorrectly. (Note: I'm aware this doesn't account for changes in month or year yet. I'll get to that once I figure out proper date spacing)
<% for i in (0..(#allLessons.count-1)) %>
<b><%= #date[i].created_at.strftime('%b %d')%></b><br/>
<% if #date[i].created_at.strftime('%d') == #date[i-1].created_at.strftime('%d') %>
<%= #date[i].created_at.strftime('%d') %> <br />
<% else %>
<%= #date[i].created_at.strftime('%d') %><br /><br />
<% end %>
<% end %>
From the controller:
#allLessons = Lesson.all
#date = Lesson.find(:all, :order => 'created_at ASC')
Any help you could lend on this would be hugely appreciated!
Blocks and iterators are where it's at.
#allLessons = Lesson.order('created_at ASC')
#dates = #allLessons.group_by { |lesson| lesson.created_at.beginning_of_day }.sort
<% #dates.each do |date, lessons| %>
<% lessons.each do |lesson| %>
<b><%= lesson.created_at.strftime("%d") %></b><br />
<% end %>
<br />
<% end %>
Annotated
First we get all of the lessons together. This is equivilant to find(:all, :order => 'created_at ASC'), but I like this newer, compact syntax
#allLessons = Lesson.order('created_at ASC')
Then we group them all together into a hash where the key is the date and the value is an array of records that were created on that day. beginning_of_day converts a DateTime into a Date where the time is set to 00:00:00. So, 2012-05-25 18:00 becomes 2012-05-25 00:00:00. This is so we can group the dates themselves without the time getting in the way
#dates = #allLessons.group_by { |lesson| lesson.created_at.beginning_of_day }.sort
#dates is now a hash where the keys are dates and the values are arrays of lessons from that date. for example, { '2012-05-24 00:00:00' => [ lesson_1 ], 2012-05-25 00:00:00' => [ lesson_2, lesson_3 ]
We then pass the hash into a block, where the key is the date, and the value is the array of lessons. This is saying, for each date...
<% #dates.each do |date, lessons| %>
Give me the lessons that belong to that date. And for each of those...
<% lessons.each do |lesson| %>
print out the date of the lesson
<b><%= lesson.created_at.strftime("%d") %></b><br />
<% end %>
before moving on to the next date, print a <br />
<br />
<% end %>

Resources