我在兩個模型之間有一個簡單的has_many關聯:
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
end
假設我有一系列書籍物件。
[#<Book:0x00007fbe329ff6f8
id: 10,
name: "book_15"
author_id: 1>,
#<Book:0x00007fbe329ff6f9
id: 15,
name: "Bible"
author_id: nil>,
#<Book:0x00007fbe329ff6f1
id: 17
name: "book_45"
author_id: 1>]
如何將此物件陣列轉換為 json 物件陣列,以便頂級將作者及其相關書籍顯示為陣列,并且沒有作者的書籍也獨立位于第一級。
像這樣:
[
{
author_id,
author_name,
books: [
{ ...book json... },
{ ...book json... },
]
},
{ ...book json ... },
{ ...book json ... }
]
在我的特定示例中,結果將如下所示:
[
{
id: 1,
name: "Dexter Willis",
books: [
{ id: 10, name: "book_15" },
{ id: 17, name: "book_45" }
]
},
{ id: 15, name: "Bible" }
]
如何才能做到這一點?提前致謝。
uj5u.com熱心網友回復:
假設books是一組書籍物件:
books_with_author, books_without_author = books.partition { |book| book.author_id }
books_grouped_by_author = books_with_author.group_by(&:author_id)
# to avoid N 1
authors = Author.where(id: books_grouped_by_author.keys)
books_with_author = books_grouped_by_author.map do |author_id, author_books|
author = authors.detect { |a| a.id == author_id }
{
id: author.id,
name: author.name,
books: author_books.map { |book| { id: book.id, name: book.name } }
}
end
books_without_author = books_without_author.map { |book| { id: book.id, name: book.name } }
books_with_author.push(*books_without_author)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445700.html
標籤:轨道上的红宝石 红宝石 ruby-on-rails-5
上一篇:外鍵只是傳遞給新表單而不是創建操作(rubyonrails)
下一篇:處理意外資料庫Nils的最佳方法
