use belongs_to instead of field for references

This commit is contained in:
shibao 2021-09-12 18:54:53 -04:00 committed by oliviasculley
parent f96956cf5e
commit 8827858204
4 changed files with 25 additions and 10 deletions

View File

@ -1,6 +1,7 @@
defmodule Cannery.Ammo.AmmoGroup do
use Ecto.Schema
import Ecto.Changeset
alias Cannery.{Accounts, Ammo, Containers, Tags}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
@ -8,10 +9,11 @@ defmodule Cannery.Ammo.AmmoGroup do
field :count, :integer
field :notes, :string
field :price_paid, :float
field :tag_id, :binary_id
field :ammo_type_id, :binary_id
field :container_id, :binary_id
field :user_id, :binary_id
belongs_to :tag, Tags.Tag
belongs_to :ammo_type, Ammo.AmmoType
belongs_to :container, Containers.Container
belongs_to :user, Accounts.User
timestamps()
end
@ -19,7 +21,15 @@ defmodule Cannery.Ammo.AmmoGroup do
@doc false
def changeset(ammo_group, attrs) do
ammo_group
|> cast(attrs, [:count, :price_paid, :notes])
|> validate_required([:count, :price_paid, :notes])
|> cast(attrs, [:count, :price_paid, :notes, :tag_id, :ammo_type_id, :container_id, :user_id])
|> validate_required([
:count,
:price_paid,
:notes,
:tag_id,
:ammo_type_id,
:container_id,
:user_id
])
end
end

View File

@ -1,6 +1,7 @@
defmodule Cannery.Containers.Container do
use Ecto.Schema
import Ecto.Changeset
alias Cannery.{Accounts}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
@ -9,7 +10,8 @@ defmodule Cannery.Containers.Container do
field :location, :string
field :name, :string
field :type, :string
field :user_id, :binary_id
belongs_to :user, Accounts.User
timestamps()
end
@ -17,7 +19,7 @@ defmodule Cannery.Containers.Container do
@doc false
def changeset(container, attrs) do
container
|> cast(attrs, [:name, :desc, :type, :location])
|> validate_required([:name, :desc, :type, :location])
|> cast(attrs, [:name, :desc, :type, :location, :user_id])
|> validate_required([:name, :desc, :type, :location, :user_id])
end
end

View File

@ -1,6 +1,7 @@
defmodule Cannery.Tags.Tag do
use Ecto.Schema
import Ecto.Changeset
alias Cannery.{Accounts}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
@ -8,7 +9,8 @@ defmodule Cannery.Tags.Tag do
field :bg_color, :string
field :name, :string
field :text_color, :string
field :user_id, :binary_id
belongs_to :user, Accounts.User
timestamps()
end

View File

@ -7,6 +7,7 @@ defmodule Cannery.Repo.Migrations.CreateTags do
add :name, :string
add :bg_color, :string
add :text_color, :string
add :user_id, references(:users, on_delete: :nothing, type: :binary_id)
timestamps()