From the reply quoted below on a related topic - which you should totally have a look on, you may use assoc_constraint/3 or foreign_constraint/3. For a more generic approach, instead of manually calling any of these functions or any other validation you might want to add like cast/4, I would recommend you do something like:
defmodule Post do
use Ecto.Schema
import Ecto.Changeset
schema "post" do
# ...
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:user_id])
|> foreign_key_constraint(:user_id)
end
end
###
params = %{body: body, user_id: user_id}
%Post{}
|> Post.changeset(params)
|> Repo.insert # {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t}