bitbldr

bitbldr

Using put_assoc for many_to_many association without the actual record

Hi! I’m trying to emulate an “enum” data type by forming a many-to-many relationship between 2 tables. Essentially I have Users and they have Roles. The roles are seeded into the database, but rarely change. I’m using the following pattern to emulate enums for roles:

roles.ex

  @superhero %Role{
    id: 1,
    name: "superhero"
  }

  @none %Role{
    id: 2,
    name: "none"
  }

  def get_by_name("superhero"), do: @superhero
  def get_by_name("none"), do: @none
...

I have a many-to-many set up between user and role schemas:
user.ex

  schema "users" do
    field :name, :string, default: ""
    field :email, :string, default: ""
    
    many_to_many :roles, MyApp.Role,
      join_through: "user_roles", on_replace: :delete
  end

role.ex

  schema "roles" do
    field :name, :string, unique: true

    many_to_many :users, MyApp.User,
      join_through: "user_roles", on_replace: :delete
  end

I would like to be able to simply change the roles a user has using something like put_assoc without doing a database lookup for the actual role record. For example, I could change my get_by_name(name) function to do a database lookup for the actual record (In fact, changing this function to do exactly that works fine), but this seems inefficient and might cause performance troubles since this function will be used extensively throughout the codebase.

I also would prefer a solution that avoids directly modifying the join table user_roles, as that seems a bit cumbersome and counter to the intuitive/succinct “ecto way” of managing associations. I’m hoping there is an efficient way to specify an existing record (where I already know the id) to add to or modify the association collection, for example passing a (list of) struct(s) with the id of the role I want to associate.

I’ve tried the following code to do this, but it raises a unique_constraint error on the roles, which leads me to think it is trying to create a new record with the same id instead of associating the existing one.

    {:ok, user} =
      User.changeset(%User{
        email: "ironman@avengers.com",
        name: "Tony Stark",
      }, attrs)
      |> put_assoc(:roles, [MyApp.Roles.get_by_name("superhero")])
      |> Repo.insert
** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * roles_pkey (unique_constraint)

If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `unique_constraint/3` on your changeset with the constraint
`:name` as an option.

The changeset has not defined any constraint.

How can I get this to associate the existing record for superhero with id: 1, instead of trying to create a new one?

Any help or thoughts about how to best approach this would be greatly appreciated. Thanks!

Marked As Solved

fuelen

fuelen

Hello.
I assume Ecto tries to create a new record, because of metadata in role structs.

"superhero" |> MyApp.Roles.get_by_name() |> Ecto.get_meta(:state)

will show you :built instead of :loaded.
Try setting state using Ecto.put_meta/2:

role |> Ecto.put_meta(state: :loaded)

Also Liked

thojanssens1

thojanssens1

Note that Ecto 3.5 comes with enum support.

PrincetonPoh

PrincetonPoh

I wasted too much time to before finding this solution. Thank you!

Where Next?

Popular in Questions Top

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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
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
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
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

We're in Beta

About us Mission Statement