Blog: Posts
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.9", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
Home Report An Issue Phoenix And Ecto Testing PhoenixBlog: Posts
You’re going to create the Posts resource in your Blog project.
Blog posts should have a title, subtitle, and content. It should also have relevant timestamp information.
erDiagram
Post {
string title
string subtitle
text content
}
Generate The Posts Resource
Use Phoenix Generators to scaffold all of the necessary boilerplate. Make sure to also define the post routes in the router.
Example Solution Generate the resource. ```elixir $ mix phx.gen.html Posts Post posts title:string subtitle:string content:text $ mix ecto.migrate ``` Then add the resource to `router.ex`. ```elixir scope "/", BlogWeb do pipe_through :browser get "/", PageController, :index resources "/posts", PostController end ``` Alternatively we can define every route individually. ```elixir scope "/", BlogWeb do pipe_through :browser get "/", PageController, :index get "/posts", PostController, :index get "/posts/new", PostController, :new post "/posts", PostController, :create get "/posts/:id", PostController, :show get "/posts/:id/edit", PostController, :edit put "/posts/:id", PostController, :update patch "/posts/:id", PostController, :update delete "/posts/:id", PostController, :delete end ```Context Functions
Now that you’ve generated the Posts resource, start your project in the IEx shell to interact with the context programmatically.
$ iex -S mix phx.server
Visit http://localhost:4000/posts to see the changes you make in the IEx shell reflected on the list of posts. Make sure to refresh the page to see updated changes.
Now, use the Blog.Posts context module to do the following in the IEx shell:
- Create a blog post
- Retrieve the blog post by it’s id.
- Edit the blog post
- List all blog posts
- Delete the blog post
Repo Functions
In the IEx shell, use the Blog.Posts.Post schema and Blog.Repo module directly to do the following:
Note that the example solutions assume that you alias both modules.
iex> alias Blog.Posts.Post
iex> alias Blog.Repo
- Create a blog post
- Retrieve the blog post by it’s id.
- Edit the blog post
- List all blog posts
- Delete the blog post
Commit Your Progress
DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.
Run git status to ensure there are no undesirable changes.
Then run the following in your command line from the curriculum folder to commit your progress.
$ git add .
$ git commit -m "finish Blog: Posts exercise"
$ git push
We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.
We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.