如何在 ROR 中通过 belongs_to 与另一个 table 的关系对数据进行分组,并使组数组的名称成为相关 table 中的名称
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
是的,你可以。
我鼓励您查看以下链接:
由于您没有提供任何数据模式,我们假设您有 authors 和 books 表,每本书都属于一位作者。
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
从 DB 中检索包含作者的书籍并使用 group_by
方法准备哈希。请注意 group_by
是 Enumerable
模块的方法,而不是 ActiveRecord
.
Book.includes(:author).group_by(&:author)
你会得到这样的东西,一个散列,键是作者,值是作者书籍的数组:
{
<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>
]
}
我听说您可以通过 group_by rails 执行此操作,但我不明白如何操作。 提前谢谢你)
我不完全明白你想要什么,但总的来说,如果你想在 belongs_to
关系上做 group_by
是的,你可以。
我鼓励您查看以下链接:
由于您没有提供任何数据模式,我们假设您有 authors 和 books 表,每本书都属于一位作者。
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
从 DB 中检索包含作者的书籍并使用 group_by
方法准备哈希。请注意 group_by
是 Enumerable
模块的方法,而不是 ActiveRecord
.
Book.includes(:author).group_by(&:author)
你会得到这样的东西,一个散列,键是作者,值是作者书籍的数组:
{
<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>
]
}