7
votes

In Rails Controller, you frequently see the code bellow in order to get only posts that belong to the current_user;

class PostsController < APIController
  def show
    current_user.posts.find(params[:id])
  end
end

What's is the best way to express that with Ecto?

1

1 Answers

8
votes

You can use Ecto.Model.assoc/2 along with the Repo functions.

To get a single item:

assoc(current_user, :posts) |> Repo.get(id)

To get a all posts for a user:

assoc(current_user, :posts) |> Repo.all()

You can also use this to compose queries:

e.g.

defmodule Post do
  use Ecto.Model

  ...

  def published(query) do
    from p in query,
      where: p.published
  end
end

assoc(current_user, :posts) |> Post.published() |> Repo.all()