Ok, I got it sort of working now, thanks!
Basically I’m doing now: Karims.Kebab.changeset(%Karims.Kebab{}, %{flavour: "Chicken"})
and my model looks like this:
defmodule Karims.Kebab do
use Ecto.Schema
import Ecto.Changeset
alias Karims.Repo
alias Karims.Kebab
schema "kebabs" do
belongs_to :food_type, Karims.Food_Type
field :flavour, :string
timestamps
end
def changeset(kebab, params \\ %{}) do
kebab
|> cast(params, [:flavour])
|> cast_assoc(:food_type, required: true)
|> validate_inclusion(:flavour, ["Donkey", "Platypus"])
end
Which works as expected, “chicken” fails the validation while “Donkey” passes.
But now I have another problem: My cast_assoc(:food_type, required: true)
wouldn’t work anymore.
After I do:
iex> food_type = Karims.Food_Type |> Karims.Repo.get_by(food: "Special Kebab")
iex> changeset = Karims.Kebab.changeset(%Karims.Kebab{}, %{flavour: "Donkey", food_type: food_type})
I get told:
** (Ecto.CastError) expected params to be a map, got: %Karims.food_type{__meta__: #Ecto.Schema.Metadata<:loaded, "food_types">, inserted_at: #Ecto.DateTime<2016-10-04 04:50:35>, food: "Special kebab", updated_at: #Ecto.DateTime<2016-10-04 09:50:35>}
in so many words and then some.
Here’s how Karims.Food_Type looks like:
defmodule Karims.Food_Type do
use Ecto.Schema
import Ecto.Changeset
alias Karims.Repo
alias Karims.Food_Type
schema "food_types" do
has_many :kebabs, Karims.Kebab
field :food, :string
timestamps
end
def changeset(food_type, params \\ %{}) do
food_type
|> cast(params, [:food])
|> validate_inclusion(:food, ["Tasty kebab", "Special Kebab"])
end
Before, with Karims.Kebab.changeset(%Karims.Kebab{flavour: "Chicken"}, %{})
cast_assoc still worked but then I couldn’t validate anything. Any ideas how this could be solved?