如果只存在一个条目,则不要在索引视图中显示删除按钮

时间:2016-05-09 18:14:54

标签: elixir phoenix-framework

User has_many EmailEmail嵌套在User资源路径中。除了验证之外,我还要确保GUI不会显示给定用户的上一封电子邮件的Delete按钮。因此,User始终至少有一个Email

user#show呈现给定用户的所有email#index的{​​{1}}模板。

如果只有一个emails列出email#index按钮,我怎么能确保Delete模板中的Email按钮无法呈现?

网络/模型/ user.ex

defmodule MyApp.User do
  use MyApp.Web, :model
  use Arc.Ecto.Model

  schema "users" do
    field :last_name, :string
    has_many :emails, MyApp.Email
[...]

网络/控制器/ user_controller.ex

[...]
def show(conn, %{"id" => id}) do
  user = 
    Repo.get!(User, id) 
    |> Repo.preload([:emails])

  conn
  |> assign(:user, user)
  |> render("show.html", changeset: changeset)
end
[...]

网络/模板/用户/ show.html.eex

  [...]
  <%= render MyApp.EmailView, "index.html", conn: @conn, 
  emails: @user.emails, user: @user %>
  [...]

网络/模板/电子邮件/ index.html.eex

<table class="table">
  <tbody>
<%= for email <- @emails do %>
    <tr>
      <td><%= email.value %></td>
      <td class="text-right">
        <%= link "Show", to: user_email_path(@conn, :show, @user, email), class: "btn btn-default btn-xs" %>
        <%= link "Edit", to: user_email_path(@conn, :edit, @user, email), class: "btn btn-default btn-xs" %>
        <%= link "Delete", to: user_email_path(@conn, :delete, @user, email), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-danger btn-xs" %>
      </td>
    </tr>
<% end %>
  </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

您可以将Delete按钮打包在if中,检查@emails中是否有多个项目:

<%= if length(@emails) > 1 do %>
  <%= link "Delete", to: user_email_path(@conn, :delete, @user, email), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-danger btn-xs" %>
<% end %>

您可能希望在length(@emails)之外计算并存储for email <- @emails,因为计算列表的长度需要O(n)时间在Elixir中。