Last active
January 31, 2019 17:26
-
-
Save marinho10/fa8decd170703b66458927aadea10d2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def upsert_user_projects(user_id, project_ids) when is_list(project_ids) do | |
{:ok, time} = Ecto.Type.cast(:naive_datetime, Timex.now()) | |
project_users = | |
project_ids | |
|> Enum.uniq() | |
|> Enum.map(fn project_id -> | |
%{ | |
user_id: user_id, | |
project_id: project_id, | |
inserted_at: time, | |
updated_at: time | |
} | |
end) | |
multi = | |
Multi.new() | |
|> Multi.delete_all( | |
:user_project_deleted, | |
UserProject | |
|> where([user_project], user_project.user_id == ^user_id) | |
) | |
|> Multi.insert_all(:user_project_inserted, UserProject, project_users) | |
case Repo.transaction(multi) do | |
{:ok, _multi_result} -> | |
{:ok, Accounts.get_user(user_id)} | |
{:error, changeset} -> | |
{:error, changeset} | |
{:error, _, changeset, _} -> | |
{:error, changeset} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment