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)
  end

in with_db_json.ex

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

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
  end

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

    Repo.all(
      from(m in Bubble, where: fragment("? BETWEEN ? AND ?", m.id, ^maths, ^num), select: m)
    )
end

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

1 Like