Ecto Association Based Request

In the Rails Controller, you often see the code below to only receive messages belonging to current_user;

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

What is the best way to express this with Ecto?

+5
source share
1 answer

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

To get one item:

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

To get all messages for the user:

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

You can also use this to compile queries:

eg.

 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() 
+6
source

Source: https://habr.com/ru/post/1234400/


All Articles