1
votes

I have two models: UserGroup and User, with a many_to_many relationship.

In my UserGroup index action I do something like this:

user_groups =
  UserGroup
  |> Repo.all
  |> Repo.preload(:users)

And, in the view, when rendering user groups, I do something like this:

def render("index.json", %{user_groups: user_groups}) do
  %{
    user_groups:
      Enum.map(user_groups, fn user_group ->
        %{
          id: user_group.id,
          name: user_group.name,
          users: user_group.users
        }
      end)
  }
end

Change! Now users have a status, and I want to show just active users.

How can I "scope" the preload of users so only those with active status are displayed?

1

1 Answers

1
votes

You can pass a partial query to Repo.preload with the where clause you want. Assuming the "active" users have user.status == "active", you can do:

user_groups =
  UserGroup
  |> Repo.all
  |> Repo.preload(users: from(u in User, where: u.status == "active"))

You can read more about this in the documentation.