繁体   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