迭代哈希

时间:2018-03-23 04:07:38

标签: ruby-on-rails hash

我正在迭代一个嵌套的哈希,它存储了一个对象的版本,因为用户已经对它进行了一段时间的编辑。在这种情况下,对象代表交易要约,并且交易的两个成员都具有交易的副本,其共享将它们链接在一起的唯一密钥。每当要么改变他们的交易报价时,两个用户的交易都被推入一个哈希,其哈希键对应于他们的user_id,然后这两个哈希都被推入一个哈希,其中包含更改日期的密钥,最后所有日期哈希都存储在主哈希中。它看起来像这样:

history_hash = {
  "2018-03-22" => {
    "97" => {
      "id" => "2",
      "Offer" => "X Y, but no Z",
      "key" => "AZ81N3"
    },
    "242" => {
      "id" => "1",
      "Offer" => "X Y Z",
      "key" => "AZ81N3"
      }
    },

  "2018-03-15" => {
    "242" => {
      "id" => "1",
      "Offer" => "X Y Z",
      "key" => "AZ81N3"
      },
    "97" => {
      "id" => "2",
      "Offer" => "nil",
      "key" => "AZ81N3"
    }
  }   
}

TradeLog表是这样的:

id |    history   |    key
------------------------------
 1 | history_hash |  "AZ81N3"

在我的展示页面上,我有两个部分:一个迭代属于两个用户的实际交易对象,第二个我希望能够点击日期并查看每个日期的交易版本。

问题是,history_hash更改了user_id的交易历史记录的保存顺序。我想一直显示左边当前登录用户制作的版本,右边的另一个交易成员版本,而不是简单地硬编码(我希望能够扩展三个逻辑 - 如果可能,党的交易)。

有没有办法可以改变hash.each循环,在其他键值对之前返回某个键值对,具体取决于我给出的一些输入?这是我当前的哈希值,用于显示信息,但当前用户的信息在左右列显示之间翻转。

    <div>
      <h4>See previous versions of traid offer:</h4>
      <ul>
        <% @traid_logs.history.each do |date, user_traid| %>
          <li>
            <div class="columns">
              <div class="column">
                <p><%= date.to_date.to_s %></p>
                <div class="columns">

                  <% user_traid.each do |user_id, traid_log| %>
                    <div class="column">
                      <%= render "traid_logs/traid_log_information", traid_log: traid_log %>
                    </div>
                  <% end %>

                </div>
              </div>
            </div>
          </li>
        <% end %>
      </ul>
    </div>

1 个答案:

答案 0 :(得分:0)

我不确定我完全理解你的问题。但是,假设@traid_logs.history返回:

{
  "2018-03-22" => {
    "97" => {
      "id" => "2",
      "Offer" => "X Y, but no Z",
      "key" => "AZ81N3"
    },
    "242" => {
      "id" => "1",
      "Offer" => "X Y Z",
      "key" => "AZ81N3"
      }
    },

  "2018-03-15" => {
    "242" => {
      "id" => "1",
      "Offer" => "X Y Z",
      "key" => "AZ81N3"
      },
    "97" => {
      "id" => "2",
      "Offer" => "nil",
      "key" => "AZ81N3"
    }
  }   
}

@history_dates = @traid_logs.history.keys.sort{|a,b| b <=> a}

(只是为了确保你的东西按时间倒序排列。)

并且:

@user_ids = ["97", "242"]

(假设“97”是当前用户而“242”是另一个用户。)

我相信你可以这样做:

<div>
  <h4>See previous versions of traid offer:</h4>
  <ul>
    <% @history_dates.each do |date| %>
      <li>
        <div class="columns">
          <div class="column">
            <p><%= date.to_date.to_s %></p>
            <div class="columns">

              <% @user_ids.each do |user_id| %>
                <div class="column">
                  <%= render "traid_logs/traid_log_information", traid_log: @traid_logs.history[date][user_id] %>
                </div>
              <% end %>

            </div>
          </div>
        </div>
      </li>
    <% end %>
  </ul>
</div>