Skip to content

Instantly share code, notes, and snippets.

@graves
Created May 15, 2016 20:55
Show Gist options
  • Save graves/1b3e385cf946611d223cb5a4a88f04e6 to your computer and use it in GitHub Desktop.
Save graves/1b3e385cf946611d223cb5a4a88f04e6 to your computer and use it in GitHub Desktop.
def insert_built_belongs_to_assoc(module, foreign_key, association_name, record) do
case Map.get(record, association_name) do
built_relation = %{__meta__: %{state: :built}} ->
relation = built_relation |> module.insert
relation_pkey_value = relation |> get_association_pkey_value
Map.put(record, foreign_key, relation_pkey_value)
_ -> Map.delete(record, foreign_key)
end
end
defp get_association_pkey_value(association) do
[primary_key] = association.__struct__.__schema__(:primary_key)
%{^primary_key => value} = association
value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment