How To Add Limit by and Order By In Ash Resource Action?


I want to add actio to the reason for picking first record from the database that matches as specific condition in a specific order. Something similar to laravel eloquent first function. Flight::first();

I want to be able to call Flight.first() and get the first record in the table.

Here is what I tried to do with Ash but it is not working. It gives the error

** (Ash.Error.Invalid) Invalid Error

* No such field limit for resource Transports.Flight
    at filter
defmodule Transports.Flight do
  use Ash.Resource,
      domain: Transports,
      data_layer: AshPostgres.DataLayer

  require Ash.Query

  postgres do
    table "flights"
    repo Transports.Repo

  actions do
    defaults [:create, :read, :update, :destroy]

    read :first do
      limit: 1

This is probably what you’re looking for:

read :first do
  prepare build(limit: 1)

Given that you’re returning the first result it’s a good idea to have a well-defined sort. You can do it in the same build like this:

read :first do
  prepare build(sort: :name, limit: 1)

EXACTLY!! that’s what I was looking for! Thanks a lot!

1 Like