bitbldr

bitbldr

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!

Showing Posts 1 to 3

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)
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!

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews