Is there any way to use active record relations? #238
-
I'm trying to pass an active record model instance to a resource class. class UserResource
include Alba::Resource
attributes :id, :email
end
user = User.create!(email: "test@example.com")
UserResouce.new(user).serialize I would like the followings to work if User model has has_many association with Post model. class User < ApplicationRecord
has_many :posts
end
class Post < ApplicationRecord
belongs_to :user
# posts table has id, user_id, content columns.
end
class UserResource
include Alba::Resource
attributes :id, :email
many :articles, resource: PostResource
end
class PostResource
include Alba::Resource
attributes :content
end
user = User.create!(email: "test@example.com")
user.posts.create!(content: "content1")
user.posts.create!(content: "content2")
user_with_posts = user.preload(:posts)
UserRecord.new(user_with_posts)
# => {"id": 1, "email": "posts": [{ "content": "content1"}, { "content": "content2" }]} Is there any way to accomplish this? |
Beta Was this translation helpful? Give feedback.
Answered by
okuramasafumi
Sep 22, 2022
Replies: 1 comment 4 replies
-
@akira-19 I think your code should work out of the box. Please let me know what error occurred if you try. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@akira-19 You can do so by splitting attributes into mandatory ones and optional ones and using
if
option.Could you try this approach and see how it goes?