Created
August 2, 2016 09:00
-
-
Save riverrun/e761911c37bab88e6b8fa4b1bb6f6892 to your computer and use it in GitHub Desktop.
Json / map in Phoenix form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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