Pheonix | Repo controller accepting range for DB request

Project name : with_db
DB name : with_db_dev
Schema : Bubble

Ive created a new FN in the controller file

in buble_conntroller.ex

def range(conn, %{"num" => number}) do
    bubbles = WithDbJson.get_bubble_range(number)
    render(conn, "index.json", bubbles: bubbles)

in with_db_json.ex

def get_bubble_range(num) do
    Repo.all(from(m in Bubble, where: <= ^(num - 60), where: >= ^num, select: m))

that accepts a range from

in router.ex

scope "/api", WithDbWeb do
    pipe_through :api
    resources "/all", BubbleController, only: [:index, :show]
    get "/:num", BubbleController, :range

the above returns the following error in the browser / terminal : bad argument in arithmetic expression

Solution in code :

 def get_bubble_range(num) do

    {num, _men} = Integer.parse(num)

    maths = num - 60

      from(m in Bubble, where: fragment("? BETWEEN ? AND ?",, ^maths, ^num), select: m)

You receive parameters as strings. You cannot do math on strings without converting them to numbers (integer/float) first.

1 Like