edmundobiglia

edmundobiglia

"user_id can't be blank" error when creating a record with "user" association

Hello all,

I’m new to Elixir and Phoenix and I’m creating a simple API for a fake project management app (Tradtrack), just for practice.

The app has two schemas: user and project. One user has many projects, so the params to create a new project must include user_id. However, even if I pass a valid user_id when creating a project, I get this error:

errors: [
    user_id: {"can't be blank", [validation: :required]}
],

Here are the user and project schemas and migrations.

  • Project migration:
defmodule Tradtrack.Repo.Migrations.CreateProjectsTable do
  use Ecto.Migration

  def change do
    create table :projects do
      add :code, :string
      add :client, :string
      add :word_count, :integer
      add :rate, :decimal
      add :total, :decimal
      add :date_received, :date
      add :delivery_date, :utc_datetime
      add :delivery_status, :boolean, default: false
      add :payment_status, :boolean, default: false
      add :notes, :string, default: ""
      add :user_id, references(:users, type: :binary_id, on_delete: :delete_all)

      timestamps()
    end

    create constraint(:projects, :word_count_must_be_greater_than_zero, check: "word_count > 0")
    create constraint(:projects, :rate_must_be_greater_than_zero, check: "rate > 0")
  end
end
  • Project schema:
defmodule Tradtrack.Project do
  use Ecto.Schema
  import Ecto.Changeset
  alias Ecto.Changeset
  alias Tradtrack.User

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  @allowed [
    :code,
    :client,
    :word_count,
    :rate,
    :date_received,
    :delivery_date,
    :delivery_status,
    :payment_status,
    :notes
  ]

  @required_fields [:code, :client, :word_count, :rate, :date_received, :delivery_date, :user_id]

  schema "projects" do
    field :code, :string
    field :client, :string
    field :word_count, :integer
    field :rate, :decimal
    field :total, :decimal
    field :date_received, :date
    field :delivery_date, :utc_datetime
    field :delivery_status, :boolean, default: false
    field :payment_status, :boolean, default: false
    field :notes, :string, default: ""
    belongs_to :user, User, foreign_key: :user_id
    timestamps()
  end

  def changeset(project \\ %__MODULE__{}, params) do
    project
    |> cast(params, @allowed)
    |> validate_required(@required_fields)
    |> check_constraint(:word_count, name: :word_count_must_be_greater_than_zero)
    |> check_constraint(:rate, name: :rate_must_be_greater_than_zero)
    |> calculate_total()
  end

  defp calculate_total(
         %Changeset{valid?: true, changes: %{word_count: word_count, rate: rate}} = changeset
       ) do
    total = Decimal.mult(word_count, rate)

    change(changeset, %{total: total})
  end
end
  • User migration:
defmodule Tradtrack.Repo.Migrations.CreateUsersTable do
  use Ecto.Migration

  def change do

    create table :users do
      add :name, :string
      add :last_name, :string
      add :email, :string
      add :nickname, :string
      add :password_hash, :string

      timestamps()
    end

    # ensures fields email and nickname are unique
    create unique_index(:users, [:email])
    create unique_index(:users, [:nickname])
  end
end
  • User schema
defmodule Tradtrack.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Ecto.Changeset
  alias Tradtrack.Project

  @primary_key {:id, :binary_id, autogenerate: true}
  @required_params [:name, :last_name, :email, :nickname, :password]
  @email_regex ~r/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/

  schema "users" do
    field :name, :string
    field :last_name, :string
    field :email, :string
    field :nickname, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    has_many :projects, Project

    timestamps()
  end

  def changeset(params) do
    %__MODULE__{}
    |> cast(params, @required_params)
    |> validate_required(@required_params)
    |> unique_constraint([:email])
    |> unique_constraint([:nickname])
    |> validate_format(:email, @email_regex)
    |> validate_length(:password, min: 6)
    |> put_password_hash()
  end

  defp put_password_hash(%Changeset{valid?: true, changes: %{password: password}} = changeset) do
    change(changeset, Bcrypt.add_hash(password))
  end

  defp put_password_hash(changeset), do: changeset
end

Any help will be much appreciated! :slight_smile:

Thank you very much!

Marked As Solved

valehelle

valehelle

In @allowed that you used to cast does not contain user_id. Can that be the problem?

Also Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

This all looks correct. Can you show some parameters that result in this error, along with the code you’re using to pass them in?

edmundobiglia

edmundobiglia

@valehelle Yes, that solved the problem! :slight_smile: Thanks a million!

Where Next?

Popular in Questions Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31265 143
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement