the-smaug
Phoenix : can't insert foreign keys in Postgres
Hi,
I’m currently trying ecto and i got a problem.
I generated REST JSON API, with foreign key constraints using CLI.
I have Topic and User
My schemas :
defmodule Api.Forum.Topic do
use Ecto.Schema
import Ecto.Changeset
schema "topics" do
field(:body, :string)
field(:title, :string)
field(:user_id, :integer, null: false)
timestamps()
end
@doc false
def changeset(topic, attrs) do
topic
|> cast(attrs, [:title, :body])
|> validate_required([:title, :body])
end
end
defmodule Api.Users.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field(:name, :string)
has_many(:topics, EkklesiaApi.Forum.Topic)
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:name])
|> validate_required([:name])
end
end
and migrations :
defmodule Api.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string
timestamps()
end
end
end
defmodule Api.Repo.Migrations.CreateTopics do
use Ecto.Migration
def change do
create table(:topics) do
add :title, :string
add :body, :text
add :user_id, references(:users, on_delete: :nothing)
timestamps()
end
create index(:topics, [:user_id])
end
end
Can’t understand why inserting {title: “Foo”, body: “bar”, user_id: 1} only insert title and body
Thanks
Marked As Solved
OvermindDL1
You are missing the user_id part there. ![]()
|> cast(attrs, [:title, :body, :user_id])
|> validate_required([:title, :body, :user_id])
Also Liked
the-smaug
With my limited experience i can’t say if one way is better than an other.
BTW thanks for the quick answer ![]()
idi527
Is there any reason that phoenix does not add these fields by default in validation ?
Casting foreign keys from outside data can open you up for some nasty vulnerabilities.
I saw a project that casted something like shop_id in their changesets and I could do whatever I wanted with them since I was practically “the owner” of every shop in their database.
The fact that it’s so easy to do in ecto + phoenix is a bit worrisome.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









