我正在学习Elixir,现在正在创建一个带有users
表和user_informations
表的应用程序。我正在尝试在user_id
中查询user_informations
,但未插入,我不明白为什么因为插入了所有其他字段。
这是user_informations表:
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
UserInformation模型:
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
插入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
答案 0 :(得分:0)
我明白了:user_id
参数必须作为变更集的额外参数给出。
user_information_changeset = Ecto.build_assoc(current_user, :user_informations,
full_name: user_information_params["full_name"],
...
user_id: current_user.user_id)