EctoCrux (EctoCrux v1.2.11)

Crud concern to use in helper's schema implementation with common Repo methods. You can use crux methods instead of ones generated by mix phx.gen.schema.

Installation

add to deps

def deps do
  [
    {:ecto_crux, "~> 1.2.4"}
  ]
end

configure (in config/config.exs)

config :ecto_crux, repo: MyApp.Repo

available parameters are:

  • :repo - specify repo to use to handle this queryable module
  • :page_size [optional] - default page size to use when using pagination if page_size is not specified
  • :order_by - default order by expression, will be used in every find_by call

tl;dr; example

defmodule MyApp.Schema.Baguette do
  use Ecto.Schema
  import Ecto.Changeset

  schema "baguettes" do
    field(:name, :string)
    field(:kind, :string)
    field(:type, :string)
  end

  def changeset(user, params \\ %{}) do
    user
    |> cast(params, [:name])
    |> validate_required([:name])
  end
end
defmodule MyApp.Schema.Baguettes do
  use EctoCrux, module: MyApp.Schema.Baguette, order_by: [asc: :name]

  # tips: this module is also the perfect place to implement
  # all your custom accessors/operations arround this schema
  # that are not covered by ecto_crux.
end

then you could (not exhaustive):

  alias MyApp.Schema.Baguettes

  # list all baguettes
  baguettes = Baguettes.all()

  # count baguettes
  count = Baguettes.count()

  # create an new baguette
  {:ok, baguette} = Baguettes.create(%{kind: "baguepi"})

  # get a baguette
  baguette = Baguettes.get("01ESRJA5F0MTWH74ZXM9GVW06Y")
  # update it
  {:ok, baguette} = Baguettes.update(baguette, %{kind: "baguepi"})
  # delete it
  Bachette.delete(baguette)


  # find all baguepi baguettes, within Repo prefix "francaise"
  baguettes = Baguettes.find_by(%{kind: "baguepi"}, [prefix: "francaise"])

  # find all baguepi baguettes, within Repo prefix "francaise", that was not soft deleted
  baguettes = Baguettes.find_by(%{kind: "baguepi"}, [prefix: "francaise", exclude_deleted: true])

  # find only baguepi baguettes that was soft deleted
  baguettes = Baguettes.find_by(%{kind: "baguepi"}, [only_deleted: true])

  # find all baguepi baguetes ordered by `kind`, overrides the default `name` ordering
  baguettes = Baguettes.find_by(%{type: "foo"}, [order_by: [asc: :kind]])

  # find all baguepi baguettes, within Repo prefix "francaise" and paginate
  %EctoCrux.Page{} = page = Baguettes.find_by(%{kind: "baguepi"}, [prefix: "francaise", page: 2, page_size: 15])

Functions you can now uses with MyApp.Schema.Baguettes are listed here.