diff --git a/lib/edges/events/action.ex b/lib/edges/events/action.ex index 6c0e0a9..e60a90d 100644 --- a/lib/edges/events/action.ex +++ b/lib/edges/events/action.ex @@ -27,7 +27,9 @@ defmodule Edges.Events.Action do """ use Ecto.Schema + import Ecto.Changeset + import Ecto.Query alias __MODULE__ alias Edges.Events.Source @@ -66,7 +68,9 @@ defmodule Edges.Events.Action do attrs |> Map.get(:person) - Repo.one(Source, person: person) || + source_query = from(s in Source, where: s.person == ^person) + + Repo.one(source_query) || Repo.insert!(%Source{person: person}) end diff --git a/mix.exs b/mix.exs index 6c00a55..67fee9b 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Edges.Mixfile do def project do [ app: :edges, - version: "0.1.0", + version: "0.2.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, elixirc_paths: elixirc_paths(Mix.env), diff --git a/test/edges/events/action_test.exs b/test/edges/events/action_test.exs new file mode 100644 index 0000000..97157bc --- /dev/null +++ b/test/edges/events/action_test.exs @@ -0,0 +1,43 @@ +defmodule Edges.Events.ActionTest do + use ExUnit.Case + + alias Edges.Events.Action + alias Edges.Events.Source + alias Edges.Repo + + setup do + :ok = Ecto.Adapters.SQL.Sandbox.checkout(Edges.Repo) + + {:ok, source} = + %Source{} + |> Source.changeset(%{person: "test source"}) + |> Repo.insert() + + {:ok, existing_source: source} + end + + describe "Action Creation" do + test "creating for an existing person uses that source", %{existing_source: source} do + person = source.person() + source_id = source.id() + + {:ok, action} = + %Action{} + |> Action.changeset(%{action: "Favorited", resource_type: "Listing", resource_id: "42", person: person}) + |> Repo.insert() + + assert ^source_id = action.source_id() + end + + test "creating for a new person creates a new source", %{existing_source: source} do + existing_id = source.id() + + {:ok, action} = + %Action{} + |> Action.changeset(%{action: "Favorites", resource_type: "Listing", resource_id: "42", person: "new guy"}) + |> Repo.insert() + + refute existing_id == action.source_id() + end + end +end