Phoenix routing: match a placeholder only if it has an entry in the database

Hi.

I’m rewriting a legacy Rails application (a web forum) in Elixir/Phoenix. This application has a route like this:

 # some routes
  resources "/users", UserController
  scope "/:curr_forum" do
      # many more routes
  end

There is no way to change the URL scheme. Now my problem: I want to match the :curr_forum route only when the :curr_forum part matches an entry in the database. If not, it should be invalidated. The reason is that when not validating the :curr_forum part it is to error prone, I often have routes that should not match but do nonetheless.

Any advice on how to solve this?

Returning a 404 for such cases accomplishes what you want, right? It would be the same behavior as hitting a non-existent route, so as long as you conn |> put_status(404) |> render(ErrorView, "404.html") |> halt() when the forum isn’t found you are all set. Is there a reason that this typical flow is an issue for you?

4 Likes

Hm. You are right and I am overthinking this. It doesn’t matter which part throws the 404, my application code or the phoenix framework. I somehow was on the trip that Phoenix has to send the 404, not my code.

Thanks for clearing my head!

1 Like