Skip to content

Instantly share code, notes, and snippets.



Last active May 24, 2020
What would you like to do?
def create_comment(attrs \\ %{}) do
|> Comment.changeset(attrs)
# TODO how to I get "post" here, to do the following step?
# |> Ecto.Changeset.put_assoc(:post, post)
|> Repo.insert()
def create(conn, %{"comment" => comment_params, "post_id" => post_id}) do
changeset = %Comment{}
|> Comment.changeset(comment_params)
|> Ecto.Changeset.put_change(:post_id, String.to_integer(post_id)) # TODO this works, but ugly string to integer?
case Staticblog.Repo.insert(changeset) do
{:ok, comment} ->
|> put_flash(:info, "Comment created successfully.")
|> redirect(to: Routes.post_path(conn, :show, post_id))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
def show(conn, %{"id" => id}) do
post = Blog.get_post!(id)
|> Repo.preload(:comments)
changeset = Blog.change_comment(%Comment{}) # TODO maybe squeeze in the here?
render(conn, "show.html", post: post, changeset: changeset)
<h1>Show Post</h1>
<%= @post.title %>
<%= @post.body %>
<%= for comment <- @post.comments do %>
<td><%= comment.text %></td>
<span><%= link "Show", to: Routes.post_comment_path(@conn, :show, @post, comment) %></span>
<span><%= link "Edit", to: Routes.post_comment_path(@conn, :edit, @post, comment) %></span>
<span><%= link "Delete", to: Routes.post_comment_path(@conn, :delete, @post, comment), method: :delete, data: [confirm: "Are you sure?"] %></span>
<% end %>
<%= render StaticblogWeb.CommentView, "form.html", Map.put(assigns, :action, Routes.post_comment_path(@conn, :create, @post)) %>
<span><%= link "Edit", to: Routes.post_path(@conn, :edit, @post) %></span>
<span><%= link "Back", to: Routes.post_path(@conn, :index) %></span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.