![](/img/trans.png)
[英]SQL Query for related Table with pair of id´s from another table (show names instead id´s)
[英]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_by
是Enumerable
模块的方法,而不是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.