返回

用 Phoenix LiveView 构建 Instagram (3):简化信息交互

后端

在用 Phoenix LiveView 构建 Instagram 系列的第 3 部分中,我们将专注于实现用户个人资料的功能。这是用户可以在其中更新个人信息并与其他用户互动的地方。我们将构建一个表单,允许用户编辑他们的个人资料信息,例如姓名、个人简历和头像。

要开始,我们需要设置路由。在 web/router.ex 中添加以下行:

scope "/", Instagr do
  live "/profile", ProfileLive, :index
end

这将创建一个新的路由,将 /profile 路径映射到 ProfileLive 模块。

接下来,我们需要在数据库中创建与个人资料相关的模型。在 schema/user.ex 中,添加以下代码:

defmodule Instagr.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
    field :bio, :string
    field :avatar_url, :string

    timestamps()
  end

  @required_fields ~w(name bio avatar_url)
  @optional_fields []

  def changeset(user, attrs) do
    user
    |> cast(attrs, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
  end
end

这个模式定义了 namebioavatar_url 字段。我们还定义了 @required_fields@optional_fields 元组,以便在更改集中使用它们。

现在我们可以构建 LiveView 了。在 lib/instagr_web/live/profile_live.ex 中,添加以下代码:

defmodule Instagr.Web.Live.ProfileLive do
  use Phoenix.LiveView

  def mount(_params, _session, socket) do
    {:ok, assign(socket, user: nil)}
  end

  def handle_params(params, _url, socket) do
    {:noreply, assign(socket, user: Repo.get(Instagr.User, params["id"]))}
  end

  def handle_event("save", %{"user" => user_params}, socket) do
    changeset = Instagr.User.changeset(socket.assigns.user, user_params)

    case Repo.update(changeset) do
      {:ok, _user} ->
        {:noreply, assign(socket, user: Repo.get(Instagr.User, socket.assigns.user.id))}
      {:error, changeset} ->
        {:noreply, assign(socket, changeset: changeset)}
    end
  end

  def render(assigns) do
    ~H"""
    <h1><%= @user.name %></h1>

    <form phx-change="save">
      <label for="name">Name</label>
      <input type="text" name="name" value={@user.name} />

      <label for="bio">Bio</label>
      <textarea name="bio">{@user.bio}</textarea>

      <label for="avatar_url">Avatar URL</label>
      <input type="text" name="avatar_url" value={@user.avatar_url} />

      <button type="submit">Save</button>
    </form>
    """
  end
end

此 LiveView 负责处理用户个人资料的编辑。它使用 mount/3 函数加载用户数据,并使用 handle_params/3 函数在路径中包含用户 ID 时加载用户数据。

handle_event/3 函数用于处理表单提交。它使用 Instagr.User.changeset/2 函数创建更改集,然后使用 Repo.update/2 函数更新数据库中的用户。

render/1 函数用于呈现 LiveView。它显示一个带有用户名称、个人简历和头像 URL 字段的表单。

现在,我们可以通过访问 /profile 路径来测试个人资料功能。您应该会看到一个表单,您可以在其中编辑自己的个人信息。

在下一部分中,我们将讨论如何处理用户上传的帖子。敬请期待!