Rails creating multidimensional array within loop - ruby-on-rails

I'm trying to loop through an array of the next 7 days, and for each, perform a query to find all the 'Time slots' that match, and add these to an object which I can loop through in my view. This is fairly simple in PHP, but I'm not sure of the syntax in rails. I have a situation where each day can have multiple 'delivery slots' available, and I need to display all these slots for the next week, by day.
So far in my controller I have
d = Date.today
d2 = d + 1.week
#days = (d..d2).to_a
#deliveries = []
#days.each do |d|
#deliveries[][dayname] = d.strftime("%a")
#deliveries[][slots] = Model.where("day = ?", d.strftime("%w"))
end
Then in my view, I want to do this
<% #deliveries.each do |d| %>
<%= d.dayname %>
<% d.slots.each do |s| %>
<%= slot data here %>
<% end %>
<% end %>
Where am I going wrong? Not quite sure of the syntax in rails where you'd use "as key => value" in php. Is this the most efficient way to go about it? It will result in 7 queries which isn't ideal
Thanks for any help

If your Model only has a day number, the slots will be the same for every week and you could do something like:
slots_by_day = Model.all.group_by(&:day)
#deliveries = (Date.today..Date.today + 6.days).each_with_object({}) do |day, dayname_groups|
dayname_groups.merge!(day.strftime('%a') => slots_by_day[day.strftime('%w').to_i])
end
It will fetch all models, group them by day number of the week and then build a hash mapping each day number with the day name ending up in a hash like:
=> {"Wed"=>[#<Model...>, #<Model...>, #<Model...>, #<Model...>],
"Thu"=>[#<Model...>, #<Model...>, #<Model...>, #<Model...>], "Fri"=>...}
The hash would be used like this:
<% #deliveries.each do |dayname, slots| %>
<%= dayname %>
<% slots.each do |s| %>
<%= slot data here %>
<% end %>
<% end %>

Related

Rails 5: loop through an array of records and indicate the new records

I'm looping through an array of records like this:
#products = Product.where(category_id: #categories).order(updated_at: :desc)
<% #products.each do |product| %>
<%= #product.title %>
<%= #product.price%>
<% end %>
And now I wan to to mark the newest records as new releases:
<% #products.each do |product| %>
<% if product.created_at <= product.created_at + 2.days %>
New release
<% end %>
<%= #product.title %>
<%= #product.price%>
<% end %>
But instead of going through each product and marking which ones is new (according to the if condition I have), it just takes the first record which returns true to the if condition and marks all of the products as new.
Any idea why this is happening and how I can fix this?
Your logic is incorrect - this line:
if product.created_at <= product.created_at + 2.days
will always be true (you're comparing a date with itself), so everything will always be marked as a new product.
Did you mean to compare the created_at date with the current date instead? If you wanted to check if a product created less than two days ago, use product.created_at >= 2.days.ago.

ruby ERB compare dates

I have a site that uses ruby (rhtml) files which I am not used to editing (more used to php). I only have access to these files to edit (so not the back-end).
In the database I have a date that I can display using:
<%= zp.date %>
which will display e.g. 14/10/2010
I can display today's date using:
<%= Date.today.strftime("%Y%m%d") %>
which will display 20160122.
What I'm trying to work out is how I can compare the dates and echo the difference and in turn display something different.
e.g.
compare <%= zp.date %> and <%= Date.today.strftime("%Y%m%d") %>.
If days difference is less than 20 echo XXX
else
If days difference between 20 - 40 echo XXX
else
If days difference between 41 - 60 echo XXX
Any help would be appreciated (links etc), code examples would be greatly appreciated.
Again to clarify I can only edit the rhtml.
Dates are directly comparable with if-statements, and computing the difference will show you the number of days between them. Assuming zp.date is in the past:
<% date_difference = Date.today - zp.date %>
<% if date_difference < 20 %>
...
<% elsif date_difference <= 40 %>
...
<% elsif date_difference <= 60 %>
...
<% else %>
Difference is greater than 60
<% end %>
Note the <% %> tags, which are used for if-logic and internal Ruby code - basically any expression that shouldn't be output (thanks #QPaysTaxes), instead of <%= %> which is the output tag.
If you don't know whether zp.date is in the past or future, you can use the abs method on the result:
<% date_difference = (Date.today - zp.date).abs %>
And if zp.date isn't actually a Date object, then parse it:
<% date_difference = (Date.today - Date.parse(zp.date)).abs %>
Older Ruby versions will need strptime when the date string is ambiguous:
<% date_difference = (Date.today - Date.strptime(zp.date, '%d/%m/%Y')).abs %>

map timestamp to DateTime

<% current_user.events.find(:all, conditions: ("start" > DateTime.now )).limit(5).each do |e| %>
<%= e.start %>
<% end %>
I get this error msg:
invalid date
this does not work because the format is not correct.
I can use e.start.to_date then I can compare the e.event with TimeDate.now but I don't know how to map the value to a DateTime.
If I do it like this:
<% current_user.events.map! { |e| e.start.to_date }.limit(5).each do |e| %>
<%= e.start %>
<% end %>
It's an array and therefore the good limit, where, select Active Record methods won't work anymore.
Basically I want to map all the start values to date then I want to compare them and show only today's events or future events but not from the past.
How would you solve this?
Can you try:
current_user.events.where("start > ?", Time.now.to_date)

Grouping by Days Created_At

I am trying to get a loop to post videos grouped by each day by created_at.
For example:
December 5, 2012 -
Video 9
Video 8
Video 7
December 4, 2012 -
Video 6
Video 5
December 3, 2012 -
Video 4
Video 3
Video 2
Video 1
videos_controller:
def index
#title = 'Hip Hop Videos, Breaking News, Videos, And Funny Shxt | HOTDROPHIPHOP'
#description = ''
#videos = Video.all
#days = Video.where(:created_at == Time.today )
end
View file:
<% #days.each do |day| %>
<div class="video-date">December 4, 2012</div>
<% #videos.each do |video| %>
<% end %>
<% end %>
I also need to get that div to show that day's date as well.
I searched around and couldn't find a solution and tried the group_by (which seemed the cleanest) but couldn't get it to work. I am a bit rusty on my Rails as I haven't touched it for months.
You can do this:
#videos = Video.where(Video.arel_table[:created_at].gteq(some_date_value))
#video_days = #videos.group_by {|video| video.created_at.to_date }
Where #video_days will be a hash in the form of {some_date_value: [{video1}, {video2}, etc], next_date_value: [{video3}, {video4}, etc], etc...}.
Since you are calling .to_date on the created_at field, it will drop all of the time information, effectively grouping everything by day.
You can loop through it like:
<% #video_days.each do |day, videos| %>
<%= day.strftime("some format") %>
<% videos.each do |video| %>
<%= #output videos how you see fit %>
<% end %>
<% end %>
The best way is to use the gem Groupdate
e.g User.group_by_day(:created_at).count
Allow you to order by day, week, hour
First of all it makes no sense to call only videos from today and then run through all videos.
I would try it this way:
Controller
#videos = Video.all(:conditions => ["created_at >= ?", Date.today.at_beginning_of_month])
View
<% Date.today.at_beginning_of_month.upto(Date.today).each do |date| %>
<%= date %>: <%= #videos.select{|u| u.created_at == date }.title %>
<% end %>
It should give you a Video list with "Date: Video Title" for the actual month.
Assumed you are using mysql and video has attribute title
I am posting the following code to help you to grasp the logic ( Surely it need re-factoring )
Controller
#videos = {}
videos = Video.order("DATE(created_at) DESC, title ASC").select("DATE(created_at) as created_at, title, id" )
videos.collect{|x| #videos[x.created_at.to_s] = #videos[x.created_at.to_s] ? #videos[x.created_at.to_s] << x.title : [x.title] }
view
<% #videos.each do |posted_date, videos| %>
<div class="video-date"><%= Date.parse(posted_date.to_s).strftime("%b %d, %Y") %> </div>
<%= videos.join(", ") %>
<% end %>

Ruby: totalling amounts

I have a Donation.rb model with an amount column that takes an integer. I want to sum all the individual donations together and show the total on the home page.
In the home_controller, I'm doing #donations = Donation.all and then in the view I do
<% sum = 0 %>
<% #donations.each do |donation| %>
<%= sum += donation.amount if donation.amount? %>
<% end %>
The problem is that this is printing the running sum each time a new donation is added to it. I just want the total sum at the end after they've all been added together.
You shouldn't be doing any calculations in the view, this stuff should be done in the controller or model if it can be. For something like this I'd do in the controller
#donations = Donation.paginate(:page => params[:page], :order => 'created_at desc', :per_page => 20)
#sum = Donation.sum(&:amount)
Then simply print out the #sum in the view
<%= #sum %>
You're getting running sum printed, because you're actually printing it with the = sign.
You need to change this line:
<%= sum += donation.amount if donation.amount? %>
With:
<% sum += donation.amount if donation.amount? %>
And then, just print the value of sum wherever you want doing:
<%= sum %>
This should print the sum once its done calculating.
<% sum = 0 %>
<% #donations.each do |donation| %>
<% sum += donation.amount if donation.amount? %>
<% end %>
<%= sum %>
It's because any instance of <%= ... %> will inline the result. The regular <% ... %> version will not.
Don't do this kind of computation in the view, though. Make a class method on Donation which will handle it for you. If you need more than one line to express a computation in a view, make a helper method, or better, a model method.

Resources