Why does Phoenix keep nil options as URL params when using route helpers?

I’ve discovered that Phoenix keeps nil options when generating URLs using the route helpers and outputs empty params.

This behaviour is different than Rails which automatically removes params which are strictly nil.

Example:

Rails routes generation does not append a query param if its value strictly equals nil, ie:

users_path(only_unregistered: nil) # => /users

whereas Phoenix outputs an empty URL param if its value is nil:

user_path(conn, :index, only_unregistered: nil) # => /users?only_unregistered=

I made this comment on Slack and a developer answered me that Phoenix is explicit and less magical than Rails…

I understand this philosophy. But I cannot find a use case where one would want to keep nil options in URL generation and voluntary outputs empty params (even in that case it should still be possible to use empty strings to get empty URL params…).

On the other hand, rejecting automatically those keys seems always practical, for example in templates when one wants to reuse current parameters to generate links (like the page param which may be there or not…).

What is your opinion in this? Do you think that Phoenix should use the Rails behaviour or not?

1 Like

No, I think the current behavior is fine. You will still receive that parameter on the server-side, and it can actually be meaningful.

As an example, if you make a filtering, you can select some option, select “no option” or don’t make any selection. If you select “no option” you could use nil value. Your parameters will still have the filtering entry, with nil value. For “no selection” you won’t have the key in the parameters at all.