简体   繁体   English

使用Ruby on Rails连接两个哈希表(dynamoDb)

[英]Join two hash Tables (dynamoDb) with Ruby on Rails

I am new to Ruby for one project only - I need to join two tables with aws dynamodb. 我是Ruby的新手,仅涉及一个项目-我需要使用AWS Dynamodb连接两个表。 Basically the equivalent of sql left join. 基本上相当于sql左连接。 But since dynamodb apparently doesn't support I need to make it happen at the array level it seems. 但是由于dynamodb显然不支持,因此我需要使其在数组级别上实现。

Currently I am querying the one just fine, but I need to bring in this other table, but I'm having a heck of a time finding a simple example for ruby with rails without using ActiveRecord (to avoid causing an overhaul on pre-existing code). 目前,我正在查询一个表,但是我需要带另一个表,但是我花了一点时间来找到一个简单的示例,说明不使用ActiveRecord的带导轨的红宝石(以避免对已有的表进行大修码)。

client = Aws::DynamoDB::Client.new
response = client.scan(table_name: 'db_current')
@items = response.items

fake output to protect the innocent 假冒产品保护无辜

db_current db_current

{"machine_id"=>"pc-123435", "type_id"=>"t-56778"}

db_type db_type

{"description"=>"Dell 5 Dev Computer", "Name"=>"Dell", "type_id"=>"t-56778"}

I thought I might have to make two: 我以为我可能必须做两个:

 client = Aws::DynamoDB::Client.new
 db_c = client.scan(table_name: 'db_current')
 @c_items = db_c.items

 client = Aws::DynamoDB::Client.new
 db_t = client.scan(table_name: 'db_type')
 @t_items = db_c.joins(db_t['type_id'])  <=== then merge them

here. 这里。

 where I'll ultimately display description/name/machine_id

But sadly no luck. 但是可惜没有运气。

I'm looking for suggestions. 我正在寻找建议。 I'd prefer to keep it simple to really understand (It might sound unreasonable, I don't want to pull in ActiveRecord just yet unless I'll be owning this project going forward). 我希望保持它的简单性以使其真正理解(这听起来可能不合理,除非我将继续拥有这个项目,否则我还不想引入ActiveRecord)。

I ended up doing it this way. 我最终以这种方式这样做。 There is probably a more elegant solution for those that are familiar with Ruby... that I am not. 对于那些熟悉Ruby的人来说,可能有一个更优雅的解决方案……我不是。

basically for each of the items in the first hash array (table), I use the ID from that one to filter on the item for the 2nd hash array. 基本上,对于第一个哈希数组(表)中的每个项目,我都使用该ID来过滤第二个哈希数组的项目。 Merging them in the process. 在此过程中合并它们。 then appending to a final destination which I'll use for my UI. 然后附加到最终目标,该目标将用于我的UI。

    @c_by_id = Array.new

    @b_items.each do |item|
        pjoin = @c_items.first {|h| h['b_id'] == item['b_id']}
        newjoin = item.merge(pjoin)
        @c_by_id.append(newjoin)
    end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM