Rails 产量 - content_for 问题 [英] Rails yield - content_for problem

查看:29
本文介绍了Rails 产量 - content_for 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下要求.

例如:有一个事务表,其中包含事务名称和金额列.我想遍历交易并显示它们的详细信息(transaction_name 和金额),最后我想在页面的头部(循环之前)部分显示总金额(所有金额的总和).(把它想象成一个汇总展示)

Ex: There is a transaction table where it has columns say, transaction_name and amount. I want to loop through the transactions and display their details (transaction_name and amount) and finally I want to display the total amount (sum of all the amounts) in the head (before the loop) section of my page. (Think about it as a summary display)

示例页面结构如下

所有交易的总和 - 200

交易金额trn1 100trn2 50trn3 50

transaction amount trn1 100 trn2 50 trn3 50

我尝试使用 yield 和 content_for 标签,但没有成功.

And I tried to use yield and content_for tag but no luck.

我的代码如下(我在我的 erb 文件中调用.)

my code is as follows (i'm calling inside my erb file.)

<%= yield :transaction_summary %> 

<table>
  <% total_amount = 0%>
  <%for transaction in @transactions%>
    <tr>
      <td><%= transaction.transaction_name %></td>
      <td><%= transaction.amount %></td>
      <% total_amount += transaction.amount %>
    </tr>
  <%end%>
  </table>

<% content_for :transaction_summary do %>
   <h1>
     Sum of all the transactions - <%= total_amount %>
   </h1>
<% end %>

还有

我在视图内使用(不在布局内)

我使用的是 rails 2.2.2

I'm using rails 2.2.2

请帮助我,如果有更好的方法请告诉我

Please help me and let me know if there is a better way

提前致谢

干杯

sameera

实际上我想做的是,在特定循环之前显示一些细节,在循环之后可以收集这些细节

例如:如果我有一个交易对象数组,我想在我的视图中的交易循环之前显示通过和失败交易的计数

Ex: If i have an array of transaction objects, I want to show a count of pass and failed transactions before the transactions loop in my view

谢谢

推荐答案

我认为您对 content_for 和 yield 的理解是错误的.:) http://guides.rubyonrails.org/layouts_and_rendering.html

I think you have the wrong idea about content_for and yield. :) http://guides.rubyonrails.org/layouts_and_rendering.html

   <h1>
     <%= @transactions.collect(&:amount).sum -%>
   </h1> 
   <table>
      <%for transaction in @transactions%>
        <tr>
          <td><%= transaction.transaction_name %></td>
          <td><%= transaction.amount %></td>
        </tr>
      <%end%>
    </table>

编辑 -

关于收集数据,我建议你把它们放在辅助方法中:

Regarding collecting data, I suggest you put them in helper methods:

#transactions_helper.rb
def transactions_total transactions
  @transactions_total ||= @transactions.collect(&:amount).sum
end

def passed_transactions transactions
  @passed_transactions ||= @transactions.collect{|transaction| transaction.passed == true}
end

def failed_transactions transactions
  @failed_transactions ||= transactions - passed_transactions(transactions)
end

刚刚注意到你对 TRON 的评论.整个干燥原则并不真正适用于执行微小的逻辑,例如遍历数组.

Just noticed your comment to theTRON. The whole dry principle doesn't really apply to executing tiny logic such as looping through a array.

这篇关于Rails 产量 - content_for 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆