Hi everyone!
Previously I only worked with an Active Record. And I want to create a comment system for news.
In AR I could use polymorphic associations for this. But this is not there.
This is my relations:
app/relations/comments_relation.rb
class CommentsRelation < ROM::Relation[:sql]
gateway :default
schema(:comments, infer: true) do
associations do
belongs_to :news
belongs_to :user
has_many :comments, foreign_key: :parent_comments_id
belongs_to :comments, as: :parent
end
end
end
app/relations/news_relation.rb
class NewsRelation < ROM::Relation[:sql]
gateway :default
schema(:news, infer: true) do
associations do
has_many :comments
end
end
end
And this is my news repository:
app/repositories/news_repository.rb
class NewsRepository < ApplicationRepository
root :news
def all
root.to_a
end
def for_id(id)
root.where(id: id)
end
def with_comments
root.combine(:comments)
end
def one_with_comments!(id)
root.by_pk(id).combine(:comments).one!
end
end
I want to get news with comments like that:
[{
id: 1,
title: 'News title',
body: 'News body',
comments: [{
id: 1,
body: 'Comment 1 body',
news_id: 1,
user_id: 1,
parent_comments_id: nil,
comments: [{
id: 2,
body: 'Comment 1 child',
news_id: 1,
user_id: 1,
parent_comments_id: 1,
comments: [{
id: 3,
body: 'Comment 1 child's comment',
news_id: 1,
user_id: 1,
parent_comments_id: 2
}]
}]
}]
I attached the diagram:
The question is also where do I need to get this data?
In CommentsRepository or in the NewsRepository ?
I suspect that I will have to write a custom SQL request. But perhaps it can be done differently.
I will be glad for any answer or help.
Thanks in advance)