User
has_many Email
和Email
嵌套在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>
答案 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中。