Phoenix and Ecto. First Steps

No Comments

Valid as of Phoenix 1.2

Show routes:
mix phoenix.routes

Generating resources:
mix phoenix.gen.html Post posts –no-model
mix phoenix.gen.json Post posts

Ecto
Types

  • :string
  • :integer
  • :map
  • :binary_id
  • :float
  • :boolean

Writing Queries
Two ways

  1. Query
    import Ecto.Query
    
    from p in context.Posts
    where p.Title.Contains("Stuff")
    select p;
    
  2. Expression
    MyApp.Post
    |> where(titlle: "Stuff")
    |> limit(1)
    

Making changes – https://hexdocs.pm/ecto/Ecto.Changeset.html
changeset = Post.changeset(post, %{title: “updated”})
Repo.update(changeset)
Repo.delete(post)

Migrations
Generate migration:
mix ecto.gen.migration [migration_name] -r [repo]

Generate schema:
mix phoenix.gen.model [Schema] [table] [fields] -r [repo]

Run/Rollback migration
mix ecto.migrate -r [repo]
mix ecto.rollback -r [repo]

Generate migration:
Does not generate schema module:
mix ecto.gen.migration [migration_name] -r [repo]

Generates both schema model and a migration:
mix phoenix.gen.model [Schema] [table] [fields] -r [repo]

To avoid specifying repo all the time:
config :my_app, ecto_repos: [MyApp.Repo]

Categories: Elixir, Phoenix, Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Loading Facebook Comments ...