How to define UserBooksResource for grouped JSON output by status? #388
-
Hello, BackgroundOnly the parts relevant to this question are included here. erDiagram
users ||--o{ user_books : ""
books ||--o{ user_books : ""
users {
int id PK
}
books {
int id PK
string title
string author
string cover_image_url
}
user_books {
int id PK
int user_id FK
int book_id FK
integer status
}
For managing the status in the UserBook model, I plan to use an enum. # app/models/user_book.rb
class UserBook < ApplicationRecord
enum :status, { unread: 0, reading: 1, finished: 2 }, prefix: true
end Here’s the setup I plan to use for UserBookResource and BookResource: class UserBookResource < BaseResource
attributes :id, :status
one :book, resource: BookResource do
attributes :id, :author, :title
end
end
class BookResource < BaseResource
attributes :id, :title, :author
attribute :coverImageUrl, &:cover_image_url
end QuestionI want to return JSON in the format below, with each status grouped into its own array. I’m having trouble achieving this structure, so any guidance or examples of how to implement this would be greatly appreciated. {
unread_books: [{
id: 1,
status: 'unread',
book: {
id: 1,
title: 'hogehoge',
author: 'hogehoge',
}
},
{
id: 2,
status: 'unread',
book: {
id: 2,
title: 'hogehoge',
author: 'hogehoge',
}
}],
reading_books: [{
same structure as above
}],
finished_books: [{
same structure as above
}]
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
https://github.com/okuramasafumi/alba?tab=readme-ov-file#inline-definition-with-albaserialize This might help. |
Beta Was this translation helpful? Give feedback.
-
@okuramasafumi # UnreadUserBooksResource and FinishedUserBooksResource are almost identical.
# Only the class name and the enum status are different.
# app/resources/reading_user_books_resource.rb
class ReadingUserBooksResource < BaseResource
many :user_books,
proc { |user_books|
user_books.order(:position).select(&:status_reading?)
},
resource: UserBookResource
end #app/resources/user_books_resource.rb
class UserBooksResource < BaseResource
attribute :unread do
UnreadUserBooksResource.new(object).serializable_hash['user_books']
end
attribute :reading do
ReadingUserBooksResource.new(object).serializable_hash['user_books']
end
attribute :finished do
FinishedUserBooksResource.new(object).serializable_hash['user_books']
end
end While this approach worked for my requirements, I’m curious if there’s a better or more idiomatic way to implement this using Alba. Could you provide some insights or an example based on the approach you suggested earlier? I’d like to learn more about how to use Alba effectively for scenarios like this. Thank you! |
Beta Was this translation helpful? Give feedback.
-
Wow, I hadn’t thought of creating data for that purpose! |
Beta Was this translation helpful? Give feedback.
@reckyy OK, how about this?