Skip to content

Commit

Permalink
Handle nested structures in string_params_for/2 (#224)
Browse files Browse the repository at this point in the history
Add support for `.string_params_for/2` to handle nested associations and
nested embeds: `has_one`, `has_many`, `embeds_one`, and `embeds_many`.
  • Loading branch information
germsvel authored Jun 23, 2017
1 parent d26fb1e commit adbcc3b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/ex_machina/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -279,9 +279,13 @@ defmodule ExMachina.Ecto do
|> Enum.into(%{})
end

defp convert_atom_keys_to_strings(struct) do
Enum.reduce struct, Map.new, fn({key, value}, acc) ->
Map.put(acc, to_string(key), value)
defp convert_atom_keys_to_strings(values) when is_list(values) do
Enum.map(values, &convert_atom_keys_to_strings/1)
end
defp convert_atom_keys_to_strings(record) when is_map(record) do
Enum.reduce record, Map.new, fn({key, value}, acc) ->
Map.put(acc, to_string(key), convert_atom_keys_to_strings(value))
end
end
defp convert_atom_keys_to_strings(value), do: value
end
35 changes: 35 additions & 0 deletions test/ex_machina/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,41 @@ defmodule ExMachina.EctoTest do
}
end

test "string_params_for/2 converts has_one association into map with strings as keys" do
article = TestFactory.build(:article)

user_params = TestFactory.string_params_for(:user, best_article: article)

assert user_params["best_article"] == %{"title" => article.title}
end

test "string_params_for/2 converts has_many associations into a list of maps with strings as keys" do
article = TestFactory.build(:article, title: "Foo")

user_params = TestFactory.string_params_for(:user, articles: [article])

assert user_params["articles"] == [%{"title" => article.title}]
end

test "string_params_for/2 converts embeds_one into a map with strings as keys" do
author = %ExMachina.Author{name: "Author", salary: 1.0}

comment_params = TestFactory.string_params_for(:comment_with_embedded_assocs, author: author)

assert comment_params["author"] == %{"name" => "Author", "salary" => 1.0}
end

test "string_params_for/2 converts embeds_many into a list of maps with strings as keys" do
links = [%ExMachina.Link{url: "https://thoughtbot.com", rating: 5}, %ExMachina.Link{url: "https://github.com", rating: 4}]

comment_params = TestFactory.string_params_for(:comment_with_embedded_assocs, links: links)

assert comment_params["links"] == [
%{"url" => "https://thoughtbot.com", "rating" => 5},
%{"url" => "https://github.com", "rating" => 4}
]
end

test "params_with_assocs/2 inserts belongs_tos that are set by the factory" do
assert has_association_in_schema?(ExMachina.Article, :editor)

Expand Down

0 comments on commit adbcc3b

Please sign in to comment.