jmaniex

jmaniex

Managing associations through an aggregate root

I have a Class struct which contains a set of Topics. I am
trying to treat Class as an Aggregate root in DDD parlance. Which
means all updates to sub-entities of Class (Topics in this case)
have to be managed by the Class. This is to maintain invariants within
the Class and provide transactional consistency within Class and its
sub entities.

Here is an outline of what I have:

def changeset(class, attrs) do
  class
  |> cast(attrs, [:name,...])
  |> cast_assoc(:class_topics)
  |> validate_required([:name, ...])
end
def create_topic(%Class{} = class, attrs \\ %{}) do
  number = length(class.topics) + 1

  new_topic =
    class.topics
    |> Enum.concat([Map.put(attrs, "number", number)])

  result = class
  |> Class.changeset(%{topics: new_topic})
  |> Repo.update()
end

This complains about cast_assoc requiring Maps (whereas in this case
Topic structs are supplied)

So I updated it to this:

def create_topic(%Class{} = class, attrs \\ %{}) do
  number = length(class.topics) + 1

  new_topic =
    class.topics
    |> Enum.map(fn i -> %{id: i.id} end)
    |> Enum.concat([Map.put(attrs, "number", number)])

  result = class
  |> Class.changeset(%{topics: new_topic})
  |> Repo.update()
end

Which also doesn’t achieve what I want.

I am doing it like this as there are additional constraints on the topics
being created - which prevents me from just creating a topic without first
preloading and validating against existing topics. (For example, I want
to ensure that there is at most 1 Topic which has a particular category
in a Class - which requires me to have them all available to validate this
when creating or updating a topic.)

I think there is something obvious I am not understanding - so I thought
I’d post the question here.

Any help would be appreciated.

First Post!

aseigo

aseigo

The code seems to be trying too hard to literally reflect the design concept you have in mind, by literally updating the Class db entry in order to create a new Topic row. Storage != responsibility.

It is entirely sensible to have create_topic in the Class module (I often do this myself as well for exclusively-owned associated data, for similar reasons as you are doing here), but trying to mimic this with storage layer interaction is a step too far imho.

Just do the validation in create_topic/2 and then … well … create a new Topic row in the db using Topic.changeset/2 and Repo.insert. Easy-peasy, and you’ll not need to work around Ecto so much, let alone have those Enum.map/2/Enum.concat/2 chains.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
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
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement