tnederlof
Self Referencing many_to_many Updating Associations Issues
EDIT ** The code now works after some help
I started a thread a few days ago with some general questions and since I am now focused and have some running code I thought it would make sense to post fresh with more direct questions.
I have Users which can have friendships and the converse of that is a reverse_friendship using the Friendships table (many_to_many relationships). My attempted code is below but I am having 2 problems.
- how to add the associations with timestamps. If I don’t add timestamps to the table in the Friendship migration the inserts run fine
- put_assoc works (User 1 has User 2 as a friend and User 2 has User 1 as a reverse friend). However when I go to add another I get a warning about on_replace, I think thats because put_assoc is essentially trying to overwrite the entire friends/reverse friends. How can I add friend/reverse_friend associations and have it be additive (Add User 2 then User 3, etc to User 1 as a friend).
User Schema
defmodule App.Users.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name, :string
field :phone_number, :string
field :username, :string
field :email, :string, null: false
many_to_many :friends, User,
join_through: "friendships",
join_keys: [from_user_id: :id, to_user_id: :id]
many_to_many :reverse_friends, User,
join_through: "friendships",
join_keys: [to_user_id: :id, from_user_id: :id]
timestamps()
end
@doc false
def changeset(user_or_changeset, attrs) do
required_fields = [:username, :name, :email, :phone_number]
user_or_changeset
|> cast(attrs, required_fields)
|> validate_required(required_fields)
end
end
User Migration
defmodule App.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string, null: false
add :username, :string, null: false
add :email, :string, null: false
add :phone_number, :string, null: false
timestamps()
end
create unique_index(:users, [:username, :email, :phone_number])
end
end
Friendship Schema
defmodule App.Users.Friendship do
use Ecto.Schema
alias App.Users.User
import Ecto.Changeset
@primary_key false
schema "friendships" do
belongs_to :from_user, User
belongs_to :to_user, User
timestamps()
end
end
Friendship Migration
defmodule App.Repo.Migrations.AddCreateFriendshipTable do
use Ecto.Migration
def change do
create table(:friendships, primary_key: false) do
add :from_user_id, references(:users)
add :to_user_id, references(:users)
add :accepted, :boolean, default: false
timestamps()
end
create unique_index(:friendships, [:from_user_id, :to_user_id])
end
end
Users Context Module
defmodule App.Users do
import Ecto.Query, warn: false
alias App.Repo
alias App.Users.User
alias App.Users.Friendship
def add_friend(user, friend_user) do
%Friendship{}
|> change()
|> put_assoc(:from_user, user)
|> put_assoc(:to_user, friend_user)
|> Repo.insert()
end
end
Marked As Solved
fuelen
- You have to define a
Friendshipschema and use it inmany_to_manyassociation instead of direct table name. Timestamps will be added automatically if you useRepo.insertorRepo.insert!, but if you want to useRepo.insert_allthen values for timestamps must be provided manually. put_assocmanages the whole collection. InsertFriendshiprecord this way:
def add_friend(user, friend_user) do
%Friendship{}
|> change()
|> put_assoc(:from_user, user)
|> put_assoc(:to_user, friend_user)
|> Repo.insert()
end
*tip: add unique composite index for from_user_id and to_user_id fields.
2
Popular in Questions
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service.
Currently when I de...
New
Hi,
I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
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
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
Hi,
is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
I have followed this StackOverflow post to install the specific version of Erlang.
And When I am running mix ecto.setup then getting fol...
New
I have a super simple question about elixir - how would I take a file like this
foo
bar
baz
and output a new file that enumerates th...
New
Other popular topics
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode.
The solution seems to be, in a hyphena...
New
I have an umbrella app.
Some of the apps inside depend on other apps in the umbrella, unsurprisingly.
I’m writing a test for one of the...
New
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service.
Currently when I de...
New
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
Hello guys,
I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Hey,
Just curious what are the main benefits of Elixir compared to Clojure?
When is Elixir more useful than Clojure and vice versa?
Th...
New
i’m a new one to elixir
which editor can i use
vs code? or atom?
Thanks! :smiley:
New
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something…
Haskell reminds me of Java, and e...
New
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
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










