Current section
Files
Jump to
Current section
Files
priv/templates/ecto_context/create_for.ex.eex
@doc """
Creates a `<%= inspect(schema) %>` associated to the given parent via `assoc_atom`.
The foreign key is always set from `assoc_atom` + `parent_id`, overriding any value in `attrs`.
Returns `{:ok, <%= singular %>}` on success, `{:error, :unauthorized}` if the scope
lacks permission, or `{:error, changeset}` on validation failure.
Permission is checked via `permission(:create, %<%= inspect(schema) %>{}, scope)`.
Add a `permission(:create, %<%= inspect(schema) %>{}, scope)` clause to control who
may create records.
## Options
* `:changeset` - changeset function to use (default: `:changeset`)
If a `changeset_permission/2` function is exported by the calling module,
it is consulted whenever a non-default `:changeset` is passed. Return
`true` to allow or `false` to deny (results in `{:error, :unauthorized}`).
"""
def create_for(scope, assoc_atom, parent_id, attrs, opts \\ []) when is_map(scope) do
EctoContext.Validate.validate_opts!(opts, [:changeset])
changeset_fn = Keyword.get(opts, :changeset, <%= inspect(default_changeset) %>)
parent_key = <%= inspect(schema) %>.__schema__(:association, assoc_atom).owner_key
with true <- (changeset_fn == <%= inspect(default_changeset) %> or
not function_exported?(__MODULE__, :changeset_permission, 2) or
apply(__MODULE__, :changeset_permission, [changeset_fn, scope])) || {:error, :unauthorized},
true <- permission(:create, %<%= inspect(schema) %>{}, scope) || {:error, :unauthorized} do
changeset =
apply(<%= inspect(schema) %>, changeset_fn, [%<%= inspect(schema) %>{}, attrs, scope])
|> Ecto.Changeset.put_change(parent_key, parent_id)
with {:ok, <%= singular %> = %<%= inspect(schema) %>{}} <-
<%= inspect(repo) %>.insert(changeset) do
if function_exported?(__MODULE__, :broadcast, 2) do
apply(__MODULE__, :broadcast, [scope, {:created, <%= singular %>}])
end
{:ok, <%= singular %>}
end
end
end