我试图在较旧的Phoenix 1.2应用程序中添加友好URL的slugs。我有新的记录写入slug并在URL中显示,但以前的条目没有更新。不仅如此,从索引视图中,链接已删除了id参数。
以前的参赛作品使用slug我错过了什么?我在应用程序中没有错误。
radio.ex
defmodule Radios.Radio do
use Radios.Web, :model
schema "radios" do
field :name, :string
field :desc, :string
field :price, :integer
field :text1, :string
field :text2, :string
field :text3, :string
field :text4, :string
field :mainimg, :string
field :mainimg2, :string
field :slug, :string
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
params = Map.merge(params, slug_map(params))
struct
|> cast(params, [:name, :desc, :price, :text1, :text2, :text3, :text4, :mainimg, :mainimg2, :slug])
|> validate_required([:name, :desc, :price, :text1, :text2, :mainimg])
end
# for writing URL as radio.name
defimpl Phoenix.Param, for: Radios.Radio do
def to_param(%{slug: slug}) do
"#{slug}"
end
end
defp slug_map(%{"name" => name}) do
slug = String.downcase(name) |> String.replace(" ", "-")
%{"slug" => slug}
end
defp slug_map(_params) do
%{}
end
end
radio_controller.ex
defmodule Radios.RadioController do
use Radios.Web, :controller
...
def show(conn, %{"id" => id}) do
radio = Repo.get_by!(Radio, slug: id)
render(conn, "show.html", radio: radio)
end
...