0

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?

3
  • 1
    Create a variable, initialize it to zero before the loop, and add value to it in the loop? Commented Dec 8, 2015 at 15:32
  • @DaveNewton that does not help, as it does not add up each value from the variable. Commented Dec 8, 2015 at 15:36
  • ... How do you figure? You're iterating over values and adding them up. What's the issue? Commented Dec 8, 2015 at 15:38

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

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.