Skip to content

Instantly share code, notes, and snippets.

@jamesmintram
Last active September 1, 2018 15:32
Show Gist options
  • Save jamesmintram/97380e8f399a2bd40b56b7b6e76a689b to your computer and use it in GitHub Desktop.
Save jamesmintram/97380e8f399a2bd40b56b7b6e76a689b to your computer and use it in GitHub Desktop.
def create_section(game, attrs \\ %{}) do
section = Ecto.build_assoc(game, :sections)
IO.puts("SECTION: #{inspect(section, pretty: true)}")
section = Proj23.Level.Section.changeset(section, attrs)
IO.puts("SECTION: #{inspect(section, pretty: true)}")
end
RESULTS
Params are: %{"title" => "some title"}
SECTION: %Proj23.Level.Section{
__meta__: #Ecto.Schema.Metadata<:built, "sections">,
game: #Ecto.Association.NotLoaded<association :game is not loaded>,
game_id: 57,
id: nil,
inserted_at: nil,
title: nil,
updated_at: nil
}
SECTION: #Ecto.Changeset<
action: nil,
changes: %{title: "some title"},
errors: [game: {"can't be blank", [validation: :required]}],
data: #Proj23.Level.Section<>,
valid?: false
>
CHANGESET
defmodule Proj23.Level.Section do
use Ecto.Schema
import Ecto.Changeset
schema "sections" do
field :title, :string
belongs_to :game, Proj23.Level.Game
timestamps()
end
@doc false
def changeset(section, attrs) do
section
|> cast(attrs, [:title])
|> cast_assoc(:game)
|> validate_required([:title, :game])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment