Rails 4 - 在表

时间:2015-12-16 12:22:01

标签: ruby-on-rails ruby-on-rails-4 activerecord

假设我有一个Emails

的集合
-------------------------------------
| **recipient** | **Subject**        |
-------------------------------------
| john          | Hello              |
-------------------------------------
| john          | Hi                 |
-------------------------------------
| john          | Whats up?          |
-------------------------------------
| jane          | Hola               |
-------------------------------------
| jane          | Que tal?           |
-------------------------------------

我想显示所有电子邮件,但是会在收件人的上下文中解释每个电子邮件的位置。像这样:

Mail #1 to: john
Subject: Hello

Mail #2 to: john
Subject: Hi

Mail #3 to: john
Subject: What's up?

Mail #1 to: jane
Subject: Hola

Mail #2 to: jane
Subject: Que tal?

到目前为止,这是我的代码:

Email.all.each do |email|
    <div>
        <div>Mail <%= ??? %> to: <%= email.recipient %></div>
        <div>Subject: <%= email.subject %></div>
    </div>
end

2 个答案:

答案 0 :(得分:0)

您可以使用each_with_index迭代器:

Email.unread.each_with_index do |email, index|
    <div>
        <div>Mail <%= index+1 %> to: <%= email.recipient %></div>
        <div>Subject: <%= email.subject %></div>
    </div>
end

答案 1 :(得分:0)

我不确定我是否理解正确,您是否正在为每个收件人寻找收到邮件的简单计数器?

counter = {}
Email.all.each do |email|
  counter[email.recipient] ||= 0
    <div>
        <div>Mail <%= counter[email.recipient] += 1 %> to: <%= email.recipient %></div>
        <div>Subject: <%= email.subject %></div>
    </div>
end