2015-12-08 33 views
0

以下循环遍历销售列并将所有4个现有产品值(例如19.99 19.99 3.99 3.99)列为相应的用户标识。如何循环并将值保存到数组中

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

现在我想结果/值保存到一个新的全局变量,并添加了各出的“价值”。所以19.99 19.99 3.99 3.99的结果应该是47.96

我完全失去了。有任何想法吗?

+1

创建一个变量,在循环之前将其初始化为零,并在循环中为其添加“value”值? –

+0

@DaveNewton对此没有帮助,因为它不会将变量中的每个值相加。 – CottonEyeJoe

+0

...你怎么看?您正在迭代值并将其添加。有什么问题? –

回答

3

你可以做这样的事情:

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

尽管在视图中有这样的代码是非常值得怀疑的。相反,您可以在控制器中获得价格并计算总计。

另请注意,您缺少一个end。我将不需要的else更改为end

0

在你的控制器,你可以创建一个即时variable prefixed by @因此它可以在您的视图

例如用在你的控制器

@total_value = 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 += value %> 
    <% else %> 
<% end %> 
0

你不应该在视图中做这种事情,甚至最糟的是创建全局变量。但无论如何:

<% @values = 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 %> 
    <% @values += value %> 
<% else %> 
<% end %> 
0

你不应该在你的视图中添加那种逻辑。创建一个视图对象类(控制器实例化)也处理所有这些。您也大概可以这样做:

user.sales.each do |sale| 
    total += find_price(sale) 
    # do more stuff 
end 

如果你问“如果current_user.id == sale.user_id”,那么你很可能就错了。

在该视图对象中,您可以使用包含所有要显示的价格并在您的视图中迭代的哈希值。

相关问题