Association preloading and pagination

In mine PersonControllerthere is an action showthat:

person = Repo.get_by(Person, nick: params["nick"])
page = Message
|> where([m], m.person_id == ^person.id)
|> where([m], m.hidden == false)
|> order_by([m], desc: m.created_at)
|> Repo.preload(:channel)
|> Repo.paginate(page: params["page"], page_size: 250)

The method paginatecomes from the Scrivener package.

Using the line, Repo.preloadI get this error:

key :__meta__ not found in: #Ecto.Query<from m in Logs.Message, where: m.person_id == ^34424, where: m.hidden == false, order_by: [desc: m.created_at]>

If I delete Repo.preload, this code will work fine. I need to pre-load the channel, because in the message template I create a link to a specific channel:

<a href='/<%= @message.channel.name %>?date=<%= date %>#<%= @message.id %>'>
  [<%= @message.created_at |> Calendar.Strftime.strftime!("%H:%M:%S") %>]
</a>

The channels that a person can send messages in one day may vary, so I would like to preload the channels. How can i do this?

+4
source share
1 answer

Repo.preload . , . :

  • Repo.preload Repo.paginate - ( , Repo.paginate , )
  • Repo.preload Ecto.Query.preload -
+2

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


All Articles