1
votes

I have a User model which has_many groups.

web/models/user.ex

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

  schema "users" do
    field :first_name, :string
    field :last_name, :string
    has_many :groups, MyApp.Group
[...]

In the user#show template I'd like to render the existing groups if there are any. If there are none I'd like to render nothing.

web/templates/user/show.html.eex

[...]
<%= if @user.groups do %>
  <h2>Groups</h2>
  <ul>
  <%= for group <- @user.groups do %>
    <li><%= group.name %></li>
  <% end %>
  </ul>
<% end %>
[...]

But that doesn't work. In Rails I'd use a @user.groups.any?. How can I do this in Phoenix?

1

1 Answers

1
votes

You can check if the groups collection isn't an empty list or use the Enum.empty?/1 function:

if @user.groups != [] do
  # ...
end

if not Enum.empty?(@user.groups) do
  # ...
end