Select fields in read action

Is it possible to define a subset of fields to be selected from a resource in a read action?

Ash.Query has a select function, so that is possible when using that directly or passing a existing read action with Ash.Query.for_read, but what if I want to keep that abstracted away in a read action?

Here is my use case:

Let’s say I have an User resource that has a bunch of attributes and relationships. I want to load the logged user from that resource, but I don’t want to store the full resource (and relationship full resources as-well) in memory if I just need a couple of its fields to use for authorization.

In that case, I want to have a read action for each resource I want to load that will return just a subset of the attributes loaded and leave the rest as nil.

I can probably do that with custom actions, but it would be nice to have it in a read action for simplicity.

Also, I know that an reasonable solution would be to have another resource for the same table with just the fields I need (ex. AuthenticatedUser). The issue is that I also need to select a subset of attributes from other relationships that need to be loaded with the User resource, meaning that I would need to create a new resource for each one of them.

Ash read actions always return structs, so all fields will be present on the structs. But if you want to avoid selecting them you can use prepare build(select: [:foo, :bar]) to limit the selected fields in a given action

Copied from Zach’s message in Discord.

1 Like

Amazing, that’s what I needed, thanks man!

1 Like