Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto association query based

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?

like image 920
Nando Sousa Avatar asked Oct 23 '15 19:10

Nando Sousa


1 Answers

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()
like image 173
Gazler Avatar answered Sep 18 '22 15:09

Gazler