简体   繁体   中英

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

I've heard that you can do this via group_by rails, but I don't understand how. Thank you in advance)

I don't fully understand what you want but in general if you want to do group_by on belongs_to relationships yes you can.

I encourage you to checkout the following links:

Since you have not presented any schema of data, let's assume you have authors and books tables, each book belongs to an author.

class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end

Retrieve books with included authors from DB and prepare a hash using group_by method. Please notice that group_by is a method of Enumerable module, not ActiveRecord .

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

You will get something like this, a hash with keys as authors with values as arrays of author's books:

{
  <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>
  ]
}

If you want names as keys just use group_by with a block:

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>
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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