TIL, 2018-03-18, Ecto.
import Ecto.Changeset
to fixundefined function cast/3
. This comes from the changeset part of Ecto. Remember,import
so they can be called without the prefix.
user
|> Ecto.Changeset.cast(attrs, [:title, :description]) → |> cast(attrs, [:title, :description])
|> Ecto.Changeset.validate_required([:title, :description])
undefined_function has_many/1
:has_many/2
exists. You need to hardcode the class where the assoc is going to.has_many :habits, HabitsTwo.Habit
- pry in pipe operator
def foo do
1..10
|> Enum.map(&(&1 * &1))
|> Enum.filter(&rem(&1, 2) == 0) |> pry
|> Enum.take(3)
end
defp pry(e) do
require IEx
IEx.pry
e
end
- Debugging in pipe
-
Last record in Ecto:
Repo.one(User)
-
Get last record in Ecto in iex: Habit > Ecto.Query.last > Repo.all -
Get first record in Ecto in iex: Habit > Ecto.Query.first > Repo.all cannot use ^user_id outside of match clauses
: Usually a sign that you haven’t imported appropriate macros fromEcto.Query
.- Phoenix token?
- Composable queries in Ecto.
defmodule MyApp.Comment do
# First post query so it's pipe-able
def for_post(query, post) do
from c in query,
join: p in assoc(c, :post)
where: p.id == ^post.id
end
def popular(query) do
query |> where([c], c.votes > 10)
end
end
recent_popular_comments = Comment
|> Comment.for_post(last_post)
|> Comment.popular
|> MyApp.Repo.all