How to define a read method for preloading associations inside a resource?

Apologies for the noob question, but I couldn't find it in the docs. Let's say I have an author resource that has_many posts. How do I use the read DSL to get an author by its ID and preload its associated posts?
3 Replies
ZachDaniel
ZachDaniel•3y ago
How are you reading the resource currently? I.e if you are running a query, you could do something like
Resource
|> Ash.Query.for_read(:read)
|> Ash.Query.load(:posts)
|> Api.read!()
Resource
|> Ash.Query.for_read(:read)
|> Ash.Query.load(:posts)
|> Api.read!()
Or you could load posts on some records you received after the fact
records |> Api.load(:posts)
records |> Api.load(:posts)
Or you could do it in the action and then they would be loaded every time you read them
read :read do
primary? true

prepare build(load: :posts)
end
read :read do
primary? true

prepare build(load: :posts)
end
That last approach might be a bad idea though
Terryble
TerrybleOP•3y ago
Wow, I didn't expect to get answers immediately. I love the first approach and I'm going to use that. Thanks so much!
ZachDaniel
ZachDaniel•3y ago
Happy to help 🙂

Did you find this page helpful?