How To: Return a computed relationship in a read.

I have a resource like Posts. Each Post has a 'top comment'. So when i'm fetching a Post or list of Posts, I will like it to include the top comment like so: post.top_comment. I'm currently trying to use a preparation to load this relationship but not sure how to execute it on the Ash.Query side of things. Any ideas here would be appreciated!
11 Replies
gordoneliel
gordonelielOP•2y ago
So what im thinking is making this into a relationship on Post, so post has_one :top_comment, Comment. What im trying to figure out now is how to hook this up to the Ash.Query engine. I think what im looking for is a way to join into Comments against some attribute, and merge that into the Post
ZachDaniel
ZachDaniel•2y ago
You can use a relationship itself to do this 🙂 oh, so you already have the relationship I'm a bit confused about the need here using Ash.Query.load should load the related value, and it should be available as thing.top_comment, right?
gordoneliel
gordonelielOP•2y ago
It does load it, but it loads all Comments . What I would like is to join Comment on Post, something like so where comment.post_id == post_id and comment.some_attribute == true, Right now its returning all Comments instead of by a specific filter on the relationship/query
ZachDaniel
ZachDaniel•2y ago
Have you added a top_comment relationship? like:
has_one :top_comment, Comment do
sort points: :desc
end
has_one :top_comment, Comment do
sort points: :desc
end
Thats just one example manual relationships can be used if it gets more complex
has_one :top_comment, Comment do
filter expr(is_top == true)
end
has_one :top_comment, Comment do
filter expr(is_top == true)
end
filters can be used as well
gordoneliel
gordonelielOP•2y ago
On man thats so beautiful! It works However, the type field in the includes on AshJsonApi is returning null for some reason, maybe something to do with the has_one?
ZachDaniel
ZachDaniel•2y ago
🤔 hard to say oh if you want to include it it needs to be configured in the json_api block explicitly i.e includes [:top_comment]
gordoneliel
gordonelielOP•2y ago
its included, and it returns the correct includes, just the type field is null
ZachDaniel
ZachDaniel•2y ago
hummm do you have a json_api type configured on Comment?
gordoneliel
gordonelielOP•2y ago
same on the relationship field on the attribute level too, id is present, type is null
ZachDaniel
ZachDaniel•2y ago
so type is null for both of them?
gordoneliel
gordonelielOP•2y ago
ah, you are right on, I didnt define it there

Did you find this page helpful?