schema "some_schema" do
embeds_many(:ingredients, Ingredients, on_replace: :delete)
field(:reason_for_preparation, :string, read_after_writes: true)
belongs_to(:staff, Staff)
belongs_to(:cuisines, Cuisines)
belongs_to(:kitchen_info, KitchenInfo)
timestamps(type: :utc_datetime)
end
@doc false
def changeset(some_schema, attrs) do
some_schema
|> cast(attrs, [:kitchen_info_id, :staff_id, :cuisines_id])
|> cast_embed(:ingredients,
required: true,
with: &Ingredients.changeset/2
)
|> validate_required([:kitchen_info_id, :cuisines_id, :staff_id])
|> foreign_key_constraint(:staff_id, name: :some_schema_staff_id_fkey)
|> foreign_key_constraint(:cuisines_id, name: :some_schema_cuisines_id_fkey)
|> foreign_key_constraint(:kitchen_info_id, name: :some_schema_kitchen_info_id_fkey)
end
end
embedded_schema do
field(:ingredients_id, :id, read_after_writes: true)
field(:required_quantity, :integer, read_after_writes: true)
field(:ingredients_name, :string, read_after_writes: true)
field(:available_quantity, :integer, read_after_writes: true)
field(:delete, :boolean, virtual: true)
what’s the best way to access that ingredients_id through the parent. since something like some_schema.ingredients.ingredients_id will not work.
def reduce_ingredients(%CuisinePreparations{} = cuisines_prep) do
item_struct = cuisines_prep.cuisines_prep_ingredients
ingredients_list = Enum.fetch!(item_struct, 0)
ingredients_map = Map.from_struct(ingredients_list)
ingredients_id = Map.get(ingredients_map, :ingredients_id)
needed_quantity = Map.get(ingredients_map, :needed_quantity)
ingredients_inv =
IngredientsInventory
|> Repo.get!(ingredients_id)
attrs = %{detailed_quantity: ingredients_inv.detailed_quantity - needed_quantity}
ingredients_inv
|> IngredientsInventory.changeset(attrs)
|> Repo.update()
end
that’s the picture of what i am trying to achieve, but the above function is not solving my problem because the Enum.fetch function above only takes one index and i have an embeds many situation. I would really appreciate some help here.