kira🌺
kira🌺
AEAsh Elixir
Created by kira🌺 on 5/3/2025 in #support
`:read`ing random entry
meow! i'd like to ask a possibly dumb question. i am currently making an inspirational quotes API. i have a /api/quote endpoint with :random action which pretty much speaks for itself - returns a random quote and its author how should i correctly define my :random action? i know how to fetch a random entry using Ecto from q in "table", order_by: fragment("RANDOM()"), limit: 1, select: q. how would i do this in my action? i am using sqlite btw and here's my resource definition
use Ash.Resource,
domain: App.Domain,
extensions: [AshJsonApi.Resource],
data_layer: AshSqlite.DataLayer

json_api do
type "quote"
end

sqlite do
table "quotes_en"

repo App.Repo
end

actions do
read :random do
get? true

prepare build(limit: 1) # made this to check if this even works
end
end

attributes do
attribute :text, :string do
primary_key? true
allow_nil? false
end

attribute :author, :string do
allow_nil? true
end
end
use Ash.Resource,
domain: App.Domain,
extensions: [AshJsonApi.Resource],
data_layer: AshSqlite.DataLayer

json_api do
type "quote"
end

sqlite do
table "quotes_en"

repo App.Repo
end

actions do
read :random do
get? true

prepare build(limit: 1) # made this to check if this even works
end
end

attributes do
attribute :text, :string do
primary_key? true
allow_nil? false
end

attribute :author, :string do
allow_nil? true
end
end
i use quote's text as primary key in my db to eliminate duplicates and to add new quotes from CSV-s and other stuff w/ ease. and i guess i won't need ids for them in the near future as you can see, i have language code in my table's name, that's because i have multiple tables with quotes in different languages. so i need to choose which table to query too...
31 replies