Skip to content

Commit

Permalink
Use association id as defined on the schema
Browse files Browse the repository at this point in the history
Problem:
- current implementation works based on convention, that association
  names always follow the pattern "#{association_name}_id". This is not
  always the case

Solution:
- use the information on schema for that association to get the owner key
  • Loading branch information
mindreframer authored and Paul Smith committed Nov 11, 2015
1 parent 0aa6d7b commit 7c67047
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/ex_machina/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,12 @@ defmodule ExMachina.Ecto do
end
end

defp put_assoc(record, association_name, association) do
association_id = "#{association_name}_id" |> String.to_atom
defp get_owner_key(record, association_name) do
record.__struct__.__schema__(:association, association_name).owner_key
end

defp put_assoc(record, association_name, association) do
association_id = get_owner_key(record, association_name)
record
|> Map.put(association_id, association.id)
|> Map.put(association_name, association)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
defmodule ExMachina.TestRepo.Migrations.CreateCompanyAccount do
use Ecto.Migration

def change do
create table(:company_accounts) do
add :name, :string
add :manager_id, :integer
end
end
end
20 changes: 20 additions & 0 deletions test/ex_machina/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ defmodule ExMachina.EctoTest do
end
end

defmodule CompanyAccount do
use Ecto.Model
schema "company_accounts" do
field :name, :string
belongs_to :user, User, foreign_key: :manager_id
end
end

defmodule Article do
use Ecto.Model
schema "articles" do
Expand Down Expand Up @@ -59,6 +67,13 @@ defmodule ExMachina.EctoTest do
user: assoc(attrs, :user)
}
end

def factory(:company_account, atts) do
%CompanyAccount{
name: "BigBizAccount",
user: build(:user)
}
end
end

test "raises helpful error message if no repo is provided" do
Expand All @@ -83,6 +98,11 @@ defmodule ExMachina.EctoTest do
}
end

test "save_record/1 works with irregular foreign_keys for belongs_to associations" do
company_account = Factory.create(:company_account)
assert company_account.user.name == "John Doe"
end

test "fields_for/2 raises when passed a map" do
assert_raise ArgumentError, fn ->
Factory.fields_for(:user_map)
Expand Down

0 comments on commit 7c67047

Please sign in to comment.