简体   繁体   English

【Rails】如何将hash转成一个数组,每个都在erb中

[英]【Rails】How to turn a hash in an array with each in erb

Want to achieve想要达到

ruby 2.6.5 ruby 2.6.5
rails 6.0.3导轨 6.0.3

Thank you for your interest.感谢您的关注。
I am creating a web app in rails.我正在 Rails 中创建一个 web 应用程序。
I was wondering if you could tell me how to join multiple tables together and then do a repeat each for each element in each.我想知道您是否可以告诉我如何将多个表连接在一起,然后对每个表中的每个元素重复一次。

Details细节

From the table below, we want to get the tasks related to the user and the information related to the tasks (the solution and the name of the company that has the solution) and put them in a hash in the array.从下表中,我们要获取与用户相关的任务以及与任务相关的信息(解决方案和拥有解决方案的公司名称),并将它们放在数组中的 hash 中。

I want to output the array we have created in this way, one at a time, using each in erb.我想 output 我们以这种方式创建的数组,一次一个,使用 erb 中的每个。

(I couldn't figure out how to turn a task in EACH and still output the company name and other information associated with the task in EACH.) (我不知道如何在 EACH 中打开任务,但仍然 output 是公司名称和与 EACH 中的任务相关的其他信息。)

Like this像这样

A suitable solution for mike task "task1
・ Company name:Dcompany Solution:「solution2」
・ Company name:Ccompany Solution:「solution3」

A suitable solution for mike task "task1
・ Company name:Acompany Solution:「solution1」

Tables

users table用户表

|id|name|
| 1|mike|
| 2|bob |

tasks table任务表

|id|task_name|user_id|
| 1|task1    |      1|
| 2|task2    |      1|
| 3|task3    |      2|

recommends table推荐表

|id|task_id|solution_id|
| 1|      1|          2|
| 2|      1|          3|
| 3|      2|          1|

solutions table解决方案表

|id|solution_name|company_id|
| 1|    solution1|         1|
| 2|    solution2|         4|
| 3|    solution3|         3|

companies table公司表

|id|name    |
| 1|Acompany|
| 2|Bcompany|
| 3|Ccompany|
| 4|Dcompany|

Tried试过了

First, I was able to join the tables as shown below, with the data I wanted as a single table.首先,我能够加入如下所示的表格,将我想要的数据作为一个表格。
However, I couldn't figure out how to extract the data from here and how to turn it around with each, so I gave up.但是,我不知道如何从这里提取数据以及如何将其转过来,所以我放弃了。

tasks = user.eager_load(:tasks)
tasks = tasks.eager_load(:recommends)
tasks = tasks.eager_load(recommends: :solutions)
tasks = tasks.eager_load(recommends: {solutions: :companies })

This is approximately how I was able to get the ideal value.这大约是我能够获得理想值的方式。

infos = []

users.each do |user|
  info = {}
  temporary_array = []
  user.companies.each do |company|
  end
  info[:detail] = temporary_array
  infos << info
end

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

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