MartinVolerich
Ash Domain functions - best practices / approach
I have an Ash Domain called Flow.Model, that has a resource called Warehouse, that in turn has a relationship to many Tank(s).
The resource has relationships properly defined.
I want to provide a function in the domain that responds with the tanks for a warehouse.
A simple implementation is (of course):
def get_tanks_from_warehouse(warehouse) when is_struct(warehouse, Flow.Model.Warehouse) do
warehouse = warehouse |> Ash.load!(:tanks)
warehouse.tanks
end
Is this the best approach to use or is there a code_gen approach that can call an action to respond with the list of the “many” child resources?
Is it “wrong” to Ash.load the relationship this way in the plain Elixir function in the domain?
I’m keen to learn the best patterns to be using for the future.
Thanks
Martin
Most Liked
barnabasJ
when you define a read action as a code interface you can also pass in a load
e.g. if you have
defmodule Domain do
resource do
resource Warehouse do
define :get_warehouse, action: read, get_by: :id
end
end
end
Domain.get_warehouse(id, load: [:tanks])
That will give you the warehouse including the tanks
zachdaniel
Nothing wrong with writing those functions, just up to you if you need the benefits of a generic action or not
Functions are a simple tool and often using a simple tool is good. Since you’re aware of what you can get from generic actions, you can ultimately decide whether or not you need a generic action or not.
I personally error on the side of making generic actions and when I need functions they typically exist for a reason and I group them in some way to indicate that reason. Like if I have common helpers for building a UI I might put those in their own module MyApp.MyDomain.LiveViewHelpers or something along those lines. But when in doubt, finding a way to either extend an existing domain action or create a new one often yields better fruit down in the long run.
MartinVolerich
Very clear and practical. Many thanks again.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









