Simon Cooper
Simon Cooper

Reputation: 1594

Friendly URLs in Phoenix 1.3 undefined error

I'm trying to implement friendly URLs in my app based on the following guide https://elixircasts.io/seo-friendly-urls-with-phoenix.
The slug is being created in the db from the post title ok, but I cannot get the post to show when looking up by the slug and get the following error:

function Driverless.Articles.get_by!/2 is undefined or private

post_controller.ex

...
  def show(conn, %{"id" => id}) do
    post = Articles.get_by!(Post, slug: id)
    render(conn, "show.html", post: post)
  end
...

post.ex

...
  def changeset(%Post{} = post, attrs) do
    attrs = Map.merge(attrs, slug_map(attrs))
    post
    |> cast(attrs, [:title, :snippet, :body, :slug])
    |> validate_required([:title, :snippet, :body])
  end

  defp slug_map(%{"title" => title}) do
    slug = String.downcase(title) |> String.replace(" ", "-")
    %{"slug" => slug}
  end
  defp slug_map(_attrs) do
    %{}
  end
...

I'm sure there's a small error somewhere, but just can't spot it.

Upvotes: 0

Views: 364

Answers (1)

Simon Cooper
Simon Cooper

Reputation: 1594

Just solved this:

Unlike the original example in Elixir casts, we leave the post controller as is:

  def show(conn, %{"id" => id}) do
    post = Articles.get_post!(id)
    render(conn, "show.html", post: post)
  end

I just made the change to:

articles.ex

From:

def get_post!(id), do: Repo.get!(Post, id)

To

def get_post!(id), do: Repo.get_by!(Post, slug: id)

Upvotes: 2

Related Questions