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.
Related
The following loop goes through the sales column and lists all 4 existing product values, like 19.99 19.99 3.99 3.99 to the corresponding user id.
<% #sales.each_with_index do |sale, index| %>
<% if current_user.id == sale.user_id %>
<% price = Warehouse.where(:product => sale.product).pluck(:mrr) %>
<%= value = price.split(',').join('.').to_f %>
<% else %>
<% end %>
Now I want to save the results/values into a new global variable and add up each out of "value". So the result of 19.99 19.99 3.99 3.99 should be 47.96.
I'm completely lost. Any Ideas?
You could do something like this:
<% total = 0 %>
<% #sales.each_with_index do |sale, index| %>
<% if current_user.id == sale.user_id %>
<% price = Warehouse.where(:product => sale.product).pluck(:mrr) %>
<%= value = price.split(',').join('.').to_f %>
<% total += value %>
<% end %>
<% end %>
<%= "Total is #{total}" %>
It is highly questionable to have code like this in the view though. You could get prices and calculate totals in your controller instead.
Also note that you are missing an end. I changed the unneeded else to an end.
In your controller you can create a instant variable prefixed by # so it can be used throughout your view
For example in your controller
#total_value = 0
And in your view
<%#sales.each_with_index do |sale, index| %>
<% if current_user.id == sale.user_id %>
<% price = Warehouse.where(:product => sale.product).pluck(:mrr) %>
<%= value = price.split(',').join('.').to_f %>
<% #total_value += value %>
<% else %>
<% end %>
You shouldn't add that kind of logic in your view. Create a view object class (that the controller instantiates) too handle all of this. You also probably can do something like:
user.sales.each do |sale|
total += find_price(sale)
# do more stuff
end
If you are asking 'if current_user.id == sale.user_id' then you most likely doing it wrong.
In that view object you could have a hash that has all the prices you want to show and iterate over that in your view.
In code:
<% #offers.each do |offer|%>
<%= offer.percentageOff%> <b>% OFF on order of</b>
<%= image_tag('1407951522',:size=>'10x10',:alt=>'Rs.')%>
<%= offer.amountforDiscount%>
<%= button_to 'Delete',{:action=>'destroy',:id=>offer.id},class: "" %>
<% end %>
I am new in rails. I want to show all the offers in a numbered list, I can't use database table because id is not in order. For example:
30 % OFF on order of Rs.2000
13 % OFF on order of Rs.1000
How do i achieve this?
Easiest way if you don't want to use each_with_index then You can define variable #count=0 and display, as loop occur it will be increment by 1
<% #count = 0 %>
<% #offers.each do |offer|%>
<%= #count += 1 %> #I guess you want this to show Sr.No
...... # your code
<% end %>
each_with_index way :
<% #offers.each_with_index do |offer, index|%>
<%= index + 1 %> # index starts from 0, so added 1 to start numbering from 1
...... # your code
<% end %>
Apologies if I am going about the wring way for this. But I have the following code and want to have a sum of it rather than two separate numbers:
<% #all_users.each do |i| %>
<%= i.liked_recipes.count %>
<% end %>
The output for this code is as follows:
12 4
What I would like the output to be would be the sum:
16
Also:
<%= #all_users.sum { |u| u.liked_recipes.count } %>
You need some way to keep track of the count:
<% total = 0 %>
<% #all_users.each do |i| %>
<% total += i.liked_recipes.count %>
<% end %>
<%= total %>
A shorter way of doing this would be to use inject
#all_users.inject(0) { |result, i| result + i.liked_recipes.count }
If #all_users is not loaded other than for these recipe counts then it is probably best to let the database do the counting:
LikedRecipe.where(:user_id => #all_users.select(:id)).count
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 %>
Is this the DRYest way to do it in ruby?
<% for item in #items %>
<%= n = n + 1 rescue n = 1 %>
<% end %>
which initializes "n" to '1" and increments it as the loop progresses (and prints it out) since this is in one my app's views
You can use a ternary operator:
<% for item in #items %>
<%= n = n ? n+1 : 1 %>
<% end %>
But, depending on what you're trying to do, I'm guessing an each_with_index would be more appropriate
<% #items.each_with_index do |item, n| %>
<%= n %>
<% end %>
You could also rely on ruby's nil coercion to an integer which results in zero.
<% for item in #items %>
<%= n = n.to_i + 1 %>
<% end %>
Um.
n = #items.size