Reputation: 19
In code:
<% @offer2.each do |offer|%>
<% @menuName=Menu.find_by_menu_item_name(offer.menuName_get)%>
<% @line_item.each do |line_item|%>
<%@validPrice=(@menuName.price)*(offer.disAmountOrPercentage)%>
<%end%>
<%end%>
I am new in rails.I want to add @validPrice += @validPrice
but it's not working inside the loop or outside the loop.So how do I get the sum of this variable.
Upvotes: 0
Views: 494
Reputation: 10251
Try this:
<% @validPrice = 0 %> #initialized with zero
<% @offer2.each do |offer|%> # 1st loop
<% @menuName=Menu.find_by_menu_item_name(offer.menuName_get)%>
<% @line_item.each do |line_item|%> # 2nd loop
<% @validPrice += (@menuName.price)*(offer.disAmountOrPercentage) %>
<%end%>
<%= @validPrice %> # you can access and print @validprice out of 2nd loop here
<%end%>
Upvotes: 1
Reputation:
Try this
<% @offer2.each do |offer|%>
<% @menuName=Menu.find_by_menu_item_name(offer.menuName_get)%>
<% @line_item.each do |line_item|%>
<%= validPrice = (@menuName.price)*(offer.disAmountOrPercentage) %>
<%end%>
<%end%>
Upvotes: 0
Reputation: 6015
You should declare @validPrice= 0
on the top of the loop. So that it will not initialize repeatedly.
<% validPrice = 0 %>
<% @offer2.each do |offer|%>
<% @menuName=Menu.find_by_menu_item_name(offer.menuName_get)%>
<% @line_item.each do |line_item|%>
<% validPrice += (@menuName.price)*(offer.disAmountOrPercentage) %>
<%end%>
<%end%>
It will be better if you would make model method for this summations, rather to run in view pages.
Upvotes: 0