Hello. I’m new to Phoenix and trying to associate a user_id to the business context.
Here is the users schema generated by phx.gen.auth
LiveView:
defmodule Balaio.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "users" do
field :email, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :confirmed_at, :naive_datetime
timestamps()
end
And here is the business schema along with its changeset. Notice it belongs to a User.
defmodule Balaio.Catalog.Business do
use Ecto.Schema
import Ecto.Changeset
alias Balaio.Accounts.User
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "business" do
field :name, :string
field :address, :string
field :description, :string
field :category, :string
field :phone, :string
field :thumbnail, :string
field :is_delivery, :boolean, default: false
belongs_to :user, User
timestamps()
end
@doc false
def changeset(business, attrs) do
business
|> cast(attrs, [
:name,
:description,
:phone,
:address,
:category,
:thumbnail,
:is_delivery,
:user_id
])
|> validate_required([
:name,
:description,
:phone,
:address,
:category,
:thumbnail,
:is_delivery,
:user_id
])
|> unique_constraint(:user_id)
end
end
And on the FormComponent, I’ve added the @form[:user_id]
hidden field.
def render(assigns) do
~H"""
<div>
<.simple_form
for={@form}
id="business-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:description]} type="text" label="Description" />
<.input field={@form[:user_id]} type="hidden" /> <-- Added this line
<:actions>
<.button phx-disable-with="Saving...">Save Business</.button>
</:actions>
</.simple_form>
</div>
"""
end
But I don’t know how I might fill the user_id
property
I really appreciate any help