Skip to content

Instantly share code, notes, and snippets.

@riverrun
Created August 2, 2016 09:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save riverrun/e761911c37bab88e6b8fa4b1bb6f6892 to your computer and use it in GitHub Desktop.
Save riverrun/e761911c37bab88e6b8fa4b1bb6f6892 to your computer and use it in GitHub Desktop.
Json / map in Phoenix form
<%= form_for @changeset, @action, fn f -> %>
<%= if @changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
</div>
<% end %>
<div class="form-group">
<%= label f, :type, class: "control-label" %>
<%= select f, :type, @workout_types, prompt: "Choose workout type", class: "form-control" %>
<%= error_tag f, :type %>
</div>
<div class="form-group">
<%= label f, :details, class: "control-label" %>
<%= textarea f, :details, rows: 10, class: "form-control" %>
<%= error_tag f, :details %>
</div>
<div class="form-group">
<%= submit "Submit", class: "btn btn-primary" %>
</div>
<% end %>
defmodule GetFit.Repo.Migrations.CreateWorkout do
use Ecto.Migration
def change do
create table(:workouts) do
add :description, :string
add :type, :string
add :details, :map
timestamps()
end
create unique_index(:workouts, [:details])
end
end
defmodule GetFit.Workout do
use GetFit.Web, :model
alias GetFit.{Movement, Repo}
schema "workouts" do
field :description, :string
field :type, :string
field :details, :map
has_many :results, GetFit.Result
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(filter(params), [:description, :type, :details])
|> validate_required([:type, :details])
|> unique_constraint(:details)
end
defp filter(%{"details" => details} = params) when is_binary(details) do
Map.put params, "details", Poison.decode!(details, keys: :atoms)
end
defp filter(params), do: params
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment