select fields from nested associations
I have two tables:
users
and user_profiles
, with a one-to-one relationship. I know it might sound a bit silly, but I don't always need the information from the profile.
Back to the point: I created a read
action for searching that looks like this:
The full_name
is a calculation field based on other fields in user_profiles
. For the search functionality, I only need the user's id and full_name — nothing more. However, when I trigger the search, it returns a whole bunch of fields, including full_name
and all other user_profile
fields.
Is there a way to modify the search
so that it only returns a simple map with just the :id
and :full_name
fields?
In Ecto terms, would be something like:
I’ve tried many things without success — such as adding Ash.Query.select(:id)
or using modify_query
, but I’m not sure how to get an alias. Another option is to do some post-processing with Ecto.map
, but I’m wondering if there’s a more elegant solution.7 Replies
When loading, if you add the
strict?: true
option, then all attributes are not selected by default
you'll still get structs back
but you won't be selecting things you don't need
is that sufficient for what you're looking for? getting an actual map back is doable, but doesn't really have much tangible benefit in my experienceAdded another tool to my toolbox =>
strict?: true
. Thanks!
Out of curiosity, what do you recommend for returning a map?There are a few ways to do it
One way, using declarative calculations:
One way, using dynamic calculations
Interesting!!
In the second one, it would be under
user.calculations.user_profile_with_less_data
If you just want to make full_name
available as a field on user
you can also easily do that
Which would give you
OMG! This is just bananas — in a good way! Thanks, Zach. I’m all set. 🙏
This is great! After applying your suggestion, I can see that I'm now making only one query instead of two. 🚀
That last way is awesome.