Fixing Rails blank select value insertion

Have spent some time getting back into the HABTM (has_and_belongs_to_many) fun and games with Rails, using association tables to model a many-many relation and a multiple select form element.

But when selecting an item from the list and submitting the form I get the following (truly appalling) error:

undefined method `name' for nil:NilClass
self.version_ids = ids

The highlighted line is the one hving the problem.

Nowhere on any of the code being worked on is there any reference to the ‘name’ and why is there a nil class?

A clue comes from looking at the submitted values which includes the following:

"release"=>{"name"=>"release_name", "version_ids"=>["", "1"], ...

There’s a blank value that is not part of the select form that is being inserted by Rails (for good reason) which accounts for the nil class (but not the name reference). discusses this and suggests some workarounds, but it could one of the things that people end up hating Rails for.

But, even after adding  a suggested fix in the controller,


Which removes the blank value; I still get the same error. This is looking like one of those Rails code typo bugs where I’m missing a capitalization or plural somewhere that will take a day to spot because of the ridiculously misleading error message: there is no nil class being passed and there’s no request for the name method of any passed object.

UPDATE: I checked another part of my application that I know to be working and uses the same method: same error. A bit more research turns up a link which suggests that downgrading to Ruby 2.1.5 (from 2.2.0) fixes the problem (with Rails 4.1.0). And this page says that upgrading to Rails 4.4.11 (to work with Ruby 2.2.4) will resolve. I have done both. Like, I said, I knew this wasn’t going to be a problem with my code, and this is exactly why people hate Ruby/Rails; I got a knowing look from a Pythonista I told this to.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s