0

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.

1
  • 1
    You should use snake_case for method names and variables. Commented Oct 7, 2014 at 10:33

3 Answers 3

1

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%>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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%>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.