Phoenix 1.3 未定义错误中的友好 URL

Friendly URLs in Phoenix 1.3 undefined error

我正在尝试根据以下指南在我的应用中实现友好 URL https://elixircasts.io/seo-friendly-urls-with-phoenix
slug 是在 db 中从 post 标题创建的,但是我无法在通过 slug 查找时显示 post 并收到以下错误:

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
...

我确定某处存在小错误,但就是无法发现。

刚刚解决了这个问题:

与 Elixir 转换中的原始示例不同,我们将 post 控制器保持原样:

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

我刚刚更改为:

articles.ex

发件人:

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

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