簡體   English   中英

如何在 ROR 中通過 belongs_to 與另一個表的關系對數據進行分組,並使組的 arrays 的名稱是相關表中的名稱

[英]How in ROR to group data by belongs_to relationships with another table and have the names of the group's arrays be names from the related table

我聽說你可以通過 group_by rails 做到這一點,但我不明白怎么做。 先感謝您)

我不完全理解你想要什么,但一般來說,如果你想在belongs_to關系上做group_by是的,你可以。

我鼓勵您查看以下鏈接:

由於您沒有提供任何數據模式,假設您有作者和書籍表,每本書都屬於一個作者。

class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end

從 DB 中檢索包含作者的書籍,並使用group_by方法准備 hash。 請注意group_byEnumerable模塊的方法,而不是ActiveRecord

Book.includes(:author).group_by(&:author)

你會得到這樣的東西,一個 hash ,其鍵為作者,值為作者書籍的 arrays:

{
  <Author id: 1, name: "Mark Twain"> => [
    <Book id: 1, title: "The Gilded Age", author_id: 1>,
    <Book id: 2, title: "Roughing It", author_id: 1>
  ],
  <Author id: 2, name: "Ernest Hemingway"> => [
    <Book id: 3, title: "The Sun Also Rises", author_id: 2>
  ]
}

如果您想將名稱作為鍵,只需將group_by與塊一起使用:

Book.includes(:author).group_by { |book| book.author.name }

{
  "Mark Twain" => [
    <Book id: 1, title: "The Gilded Age", author_id: 1>, 
    <Book id: 2, title: "Roughing It", author_id: 1>
  ], 
  "Ernest Hemingway" => [
    <Book id: 3, title: "The Sun Also Rises", author_id: 2>
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM