Reputation: 47
I'm learning Elixir and now creating an application with a users
table and a user_informations
table. I'm trying to query for user_id
in user_informations
but it was not inserted, and I don't understand why because all other fields were inserted.
Here's the user_informations table:
def change do
create table(:user_informations, primary_key: false) do
add :user_information_id, :uuid, primary_key: true
add :user_id, references(:users, [column: :user_id, type: :uuid])
add :full_name, :string
add :job_title, :string
add :address, :string
add :city, :string
add :country, :string
add :phone_number, :integer
add :bio, :string
timestamps()
end
create unique_index(:user_informations, [:user_information_id])
end
The UserInformation model:
defmodule MyApp.Accounts.UserInformation do
use Ecto.Schema
alias MyApp.Accounts
import Ecto.Changeset
@primary_key {:user_information_id, Ecto.UUID, autogenerate: true}
@foreign_key_type Ecto.UUID
schema "user_informations" do
field :full_name, :string
field :job_title, :string
field :address, :string
field :city, :string
field :country, :string
field :phone_number, :integer
field :bio, :string
belongs_to :users, Accounts.User, foreign_key: :user_id
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def user_details_changeset(struct, params \\ %{}) do
struct
|> cast(params, [:full_name, :job_title, :address, :city, :country, :phone_number, :bio])
|> validate_required([:full_name])
|> validate_length(:full_name, min: 2)
end
end
The function inserting the changeset of user_informations
:
def update(conn, %{"user_information" => user_information_params}) do
current_user = Guardian.Plug.current_resource(conn)
user_information_changeset = Ecto.build_assoc(current_user, :user_informations,
full_name: user_information_params["full_name"],
job_title: user_information_params["job_title"],
address: user_information_params["address"],
city: user_information_params["city"],
country: user_information_params["country"],
phone_number: user_information_params[:phone_number],
bio: user_information_params["bio"])
Repo.insert(user_information_changeset)
conn
|> put_flash(:info, "Success!")
|> redirect(to: page_path(conn, :index))
end
Upvotes: 0
Views: 534
Reputation: 47
I figured it out: The user_id
argument must be given as an extra argument to the changeset.
user_information_changeset = Ecto.build_assoc(current_user, :user_informations,
full_name: user_information_params["full_name"],
...
user_id: current_user.user_id)
Upvotes: 0