迭代哈希时首先返回特定键



我正在迭代一个嵌套哈希,该哈希存储了用户随着时间的推移编辑对象的版本。在这种情况下,对象代表交易报价,交易的两个成员都有一个交易副本,该副本共享一个将它们链接在一起的唯一键。每当任何一方更改他们的交易报价时,两个用户的交易都会被推送到一个哈希中,其中包含与其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"
}
}   
}

交易日志表是这样的:

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>

我不确定我是否完全理解你的问题。但是,假设@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>

最新更新