Is there a way to do a 'limit' on a relationship?

My use case is eventually an aggregate, like 'count of the last 10 posts that are unpublished'. Was thinking I could get something working if I set up a relationship that was 'most recent 10 posts', and then an aggregate count on that relationship, but not seeing anything on how that'd work. Any ideas?
7 Replies
ZachDaniel
ZachDaniel2d ago
you can indeed:
has_many ... do
limit 10
sort foo: :asc
end
has_many ... do
limit 10
sort foo: :asc
end
oh, wait I guess you can't 🤔 I really thought you could do that 😓 but you can limit an aggregate FWIW but apparently only the inline calculation type of aggregate. Wow, how does everyone ask something innocent and stumble into a mess 😜
calculate :count_of_last_ten_posts_that_are_unpublished, :integer, expr(
count(posts, query: [limit: 10, sort: [inserted_at: :desc], filter: published == true])
)
calculate :count_of_last_ten_posts_that_are_unpublished, :integer, expr(
count(posts, query: [limit: 10, sort: [inserted_at: :desc], filter: published == true])
)
Something like this should work though And thank you for being the first person to use the new forum setup ❤️ We could support limit on aggregate DSL and on has_many relationships though FWIW Feel free to open proposals for both 😄
pikdum
pikdumOP2d ago
* Cannot set limit on aggregate query
hm i like the idea of doing the limit on a has_many relationship, that seems pretty clean https://github.com/ash-project/ash/blob/f6688fcc71b750f8d96222ec8eb157b0eff523ea/lib/ash/query/aggregate.ex#L523 getting this even if it's an inline calculation type aggregate rather than an aggregate count type
ZachDaniel
ZachDaniel2d ago
huh. Maybe I'm wrong
pikdum
pikdumOP2d ago
i'll make a proposal for limits + sort on a has_many relationship
ZachDaniel
ZachDaniel2d ago
right-o you can't do it apparently 😢 You can definitely do sort just not limit apparently. I'll have to look into why limit isn't supported on aggregate queries
pikdum
pikdumOP2d ago
https://github.com/ash-project/ash/issues/2012 - made this so I think right now my best bet might be to just do things through code, like: * read action for getting last 10 posts that are unpublished * Enum.count or similar
ZachDaniel
ZachDaniel2d ago
Yeah, that would work. You could also see what happens if you do this:
has_many :last_ten... do
read_action :an_action_with_a_limit
end
has_many :last_ten... do
read_action :an_action_with_a_limit
end

Did you find this page helpful?