rails/rails — pull request #11696 by egilburg (2013-08-01 07:45:47+00:00)
Title: Select nil value if passed nil option and no explicit :selected value

I had a model with an attribute that could have either a nil or a non-nil value, and in the database one record's value was nil while others' werent. I was surprised that when doing something as following (simplified example):

```erb
<%= form_for @my_model do |f| %>
<% select_options = [ ['Nothing', nil], ['Foo', 'foo'], ['Bar', 'bar'] ] %>
<%= f.select :my_attr, select_options %>
<% end %>
```

The 'Nothing' option was *not* selected if `@my_model.my_attr` was nil, yet other options were selected fine if the model had the matching value.

Since the `select` helper silently casts a `nil` option value to an empty string (instead of, say, raising a nil object error), I expected that it would also be able to match it against a nil attribute for the selected element.

This PR fixes this by casting the implied `:selected` option to be an empty string, so it correctly finds a matching empty option.

I also added a second regression test to ensure that an explicitly passed `:selected => nil` is not treated like empty string (to preserve existing behaviour documenting that `:selected => nil` forces no option to be selected. I realize this may be a discrepancy, because `f.select :my_attr, select_options` will now behave differently than `f.select :my_attr, select_options, @my_model.my_attr` (if `@my_model.my_attr` returns nil), but I still think it's less surprising than current behaviour.