kamaroly

kamaroly

How to Extract a Relationship into a Separate Module for Reuse in `Ash`?

I’m working on a feature that lets users add custom fields to records. For this, I have three resources:

  1. FieldType with columns name and description.
  2. Field with columns name, field_type_id, description, and options.
  3. FieldResourceRecord with columns field_id, resource_name, resource_record_id, and value.

Any resource needing custom fields will have a one-to-many relationship with FieldResourceRecord where resource_name matches ResourceWithManyFields.

Currently, I’m defining the has_many :fields, MyApp.Fields.FieldResourceRecord relationship on each resource. Is there a way to centralize this relationship, similar to how we handle preparations, changes, and manual_actions?

Marked As Solved

kamaroly

kamaroly

It was not working. I fixed it like below:

defmodule Hr.Extensions.CustomFields.Transformers.AddCustomFields do
  use Spark.Dsl.Transformer
  import Ash.Expr

  @doc """
  Automatically add relationship to the FieldResourceRecord on any given resource
  """
  def transform(dsl) do
    Ash.Resource.Builder.add_new_relationship(
      dsl,
      :has_many,
      :fields,
      Hr.Fields.FieldResourceRecord,
      destination_attribute: :resource_record_id,
      filters: expr(resource_name == get_resource_name(dsl))
    )
  end

  defp get_resource_name(dsl) do
    dsl.persist.module
    |> Atom.to_string()
    |> String.replace("Elixir.", "")
  end
end

Also the error message says it requires filter options even if it has been passed. So, I figured out that the issues is in the error messages.

The error message should report missing destination_attribute instead of destination_field, and it should report missing filters instead of filter.

Error showing missing filter instead of filters

Error showing destination field missing nstead of destination_attribute

Also Liked

zachdaniel

zachdaniel

Creator of Ash

You can centralize it by writing an extension, although for just one relationship it may be sort of a nuclear option :slight_smile:

defmodule YourApp.CustomFields do
  use Spark.Dsl.Extension, 
    transformers: [YourApp.CustomFields.Transformers.AddCustomFields]
end

defmodule YourApp.CustomFields.Transformers.AddCustomFields do
  use Spark.Dsl.Transformer

  def transform(dsl) do
    dsl
    |> Ash.Resource.Builder.add_new_relationship(:has_many, :fields, MyApp>Fields.FieldResourceRecord)
  end
end

Then you can do

use Ash.Resource, extensions: [YourApp.CustomFields]
zachdaniel

zachdaniel

Creator of Ash

Make sure to import Ash.Expr

import Ash.Expr

and then you can use it like so:

    Ash.Resource.Builder.add_new_relationship(
      dsl,
      :has_many,
      :fields,
      Hr.Fields.FieldResourceRecord,
      destination_attribute: :resource_record_id,
      filter: expr(resource_name == "Hr.People.Person")
     )

EDIT: I’m pretty sure that the filter option should “just work” like that, but let me know if not.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement