Adding a query string to a redirection

Hi

How can I add a query string like ?foo=bar?

    redirect(conn,
      to:
        Routes.user_path(
          conn,
          :show_user,
          some_param,
          other_param
        )
    )

I can’t find an option for adding a query string in the redirect helper.

2 Likes

That’s because redirect works with any path/url and get params are just a part of them:

        Routes.user_path(
          conn,
          :show_user,
          some_param,
          other_param,
          foo: "bar"
        )
2 Likes

Actually the value of my parameter is a boolean, so I wanted to convert to 1 or 0, like:

active: is_active ? 1 : 0

What is the reason that Elixir doesn’t have a ternary operator? How would you write that?

if(is_active, do: 1, else: 0)

The above is hardly longer than something akin to a ternary operator, but using the default elixir keyword syntax. Meaning nothing had to be created to support it.

2 Likes

Thank you!

By the way, do you think it’s safe to insert user input in a query string value (comment below)?

redirect(conn,
      to:
        Routes.user_path(
          conn,
          :show_user,
          some_param,
          other_param,
          foo: some_user_input    # <- is this safe?
        )
    )

active: is_active && 1 || 0

This is not a recommended pattern, and it can fail in a couple of surprising ways (specifically if the 1 in the above example where nil or false because it interprets it as active: (is_active && 1) || 0), but it’s the bash’ism style, that works in Elixir too. ^.^;