Skip to content

Commit

Permalink
Allow setting associations to nil
Browse files Browse the repository at this point in the history
Previously the catchall was falling through to the list case and trying
to enumerate `nil`. This commit adds a guard to the list condition to
ensure that doesn't happen again, then adds a new condition to handle
`nil`.

I _think_ this should be handling all cases now, so it also removes the
catchall. This way, if it fails in a way we didn't expect, it should
give an obvious failure that there was no matching case.

Fixes #191
  • Loading branch information
jsteiner committed Jan 27, 2017
1 parent d2d901e commit d4108bd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/ex_machina/ecto_strategy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,19 @@ defmodule ExMachina.EctoStrategy do
case original_assoc do
%{__meta__: %{__struct__: Ecto.Schema.Metadata, state: :built}} ->
cast(original_assoc)

%{__struct__: _} ->
original_assoc

%{} ->
assoc_type = schema.__schema__(:association, assoc).related
assoc_type |> struct |> Map.merge(original_assoc) |> cast
_list ->

list when is_list(list)->
Enum.map(original_assoc, &(cast(&1)))

nil ->
nil
end
end
end
6 changes: 6 additions & 0 deletions test/ex_machina/ecto_strategy_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ defmodule ExMachina.EctoStrategyTest do
assert user.id != nil
end

test "insert/1 sets nil values" do
model = TestFactory.insert(:article, author: nil)

assert model.author == nil
end

test "insert/1 casts bare maps" do
model = TestFactory.insert(:article, author: %{net_worth: 300})

Expand Down

0 comments on commit d4108bd

Please sign in to comment.