Skip to content

Instantly share code, notes, and snippets.

@talum
Created August 23, 2017 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talum/f36329b824d78582fc72a7bbb9c11eaf to your computer and use it in GitHub Desktop.
Save talum/f36329b824d78582fc72a7bbb9c11eaf to your computer and use it in GitHub Desktop.
programming_phoenix ch 7

Programming Phoenix Ch. 7

  • database constraints, adding associations with references p. 109 - makes sure the category_id referenced in videos exists
  • i.e. make the database maintain integrity
  • uniqueness constraint on categories, to prevent dupes. esp. when running seed file twice

Ecto Queries

  • are composable, can define in chunks
  • This strategy works because Ecto defines something called the queryable protocol. from receives a queryable, and you can use any queryable as a base for a new query. (p. 112)
    Category
    |> Category.alphabetical
    |> Category.names_and_ids
  categories = Repo.all query
assign(conn, :categories, categories) end

Ecto Queries Deeper

"Repo.one doesn’t mean “return the first result.” It means “one result is expected, so if there’s more, fail.” (p. 115)

  • query normalization at compile time, means it's easier to find type errors (querying a text field for a string)
  • using the ^ operator to pattern match without assignment
  • keep functions with side effects in the controller
  • as long as it's queryable, Repo can accept it

Fragments

"A query fragment sends part of a query directly to the database but allows you to construct the query string in a safe way."

  • escape hatch for writing custom queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment