Many to Many: how to link to existing table by field`s value

Hello! I have some trouble with M:M associations. I have a tags table that has one field for a single tag. I want a new user to enter an existing in the database tag to link to this existing table.

For instance, I have user №1 with the tag “new_tag”. So if user №2 enter a tag “new_tag” for himself I want that his table was connected to the existing one tag, that created user №2 (hope I said it right, English is not my first language)

here is my migration for tag table:

  def change do
    create table(:tags) do
      add :name, :string
      timestamps()
    end
 end

here is the migration for join table:

    create table(:user_personal_tags, primary_key: false) do
      add :user_personal_id, references(:users_personal, on_delete: :nothing), null: false, primary_key: true
      add :tags_id, references(:tags, on_delete: :nothing), null: false, primary_key: true
      timestamps()

    create index(:user_personal_tags, [:user_personal_id])
    create index(:user_personal_tags, [:tags_id])

For now, when the user creates a tag new table entry with a different id for tag is created.

Thanks! :smiley:

Hi! I hope that I understood correctly your problem.

:tags table gets new tag_id.

I would create a unique index on the name field in :tags table.

create index(:tags, [:name], unique: true)

This will throw an error if you try to insert an existing tag name.