Skip to content

Instantly share code, notes, and snippets.

@josefrichter
Last active May 24, 2020 14:00
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 josefrichter/831c625e7e8f7f253862525fa19e03d5 to your computer and use it in GitHub Desktop.
Save josefrichter/831c625e7e8f7f253862525fa19e03d5 to your computer and use it in GitHub Desktop.
def create_comment(attrs \\ %{}) do
%Comment{}
|> Comment.changeset(attrs)
# TODO how to I get "post" here, to do the following step?
# |> Ecto.Changeset.put_assoc(:post, post)
|> Repo.insert()
end
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} ->
conn
|> 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)
end
end
def show(conn, %{"id" => id}) do
post = Blog.get_post!(id)
|> Repo.preload(:comments)
changeset = Blog.change_comment(%Comment{}) # TODO maybe squeeze in the post.id here?
render(conn, "show.html", post: post, changeset: changeset)
end
<h1>Show Post</h1>
<ul>
<li>
<strong>Title:</strong>
<%= @post.title %>
</li>
<li>
<strong>Body:</strong>
<%= @post.body %>
</li>
</ul>
<strong>Comments:</strong>
<table>
<%= for comment <- @post.comments do %>
<tr>
<td><%= comment.text %></td>
<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>
</td>
</tr>
<% end %>
</table>
<%= 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