How to pattern match on two kind of parameters in action with phoenix

tajihiro Source

I would like to match two kind of parameter set. If params come from out of IndexController, receive main_id only. But if params come from same page with index_path(@conn, :index, main_id) and select box value.

IndexController.ex

defmodule IndexController do
  def index(conn, %{"main_id" => main_id, "sub_id" => sub_id}) do
    render(conn, "index.html")
  end
end

index.html.eex

<%= form_for @conn, index_path(@conn, :index, main_id), fn f -> %>
  <%= select f, :sub_id, Enum.map(@items, &{&1.item_name, &1.id}) %>
<% end %>

How can I write router.ex match with two kind of parameter set?

get "/index/:main_id", IndexController, :index
post "/index/:main_id/:sub_id", IndexController, :index
elixirphoenix-framework

Answers

answered 3 months ago Cyzanfar #1

It seems like you would need to handle optional parameters and this is the way I would go about doing that:

defmodule IndexController do
  def index(conn, %{"main_id" => main_id} = params) do
    # retrieve sub_id from parameter with a nil fallback
    sub_id = params |> Map.get("sub_id", nil)
    render(conn, "index.html")
  end
end

Here i'm pattern matching on the "main_id" key and then retrieving the sub_id from the params variable.

The reason why you don't want to pattern match on both main_id and sub_id in the argument params is that, as you said, sub_id will only be present if the controller action is hit from a get request coming from the same index path.

comments powered by Disqus