I had a weird problem. I defined a collection_select in my form, something like this:
<%= f.collection_select :campaign_id, @campaigns, :id, :title %>
When I went to the form, the page loaded, and the select populated correctly. However, when I submitted the form, I would get the “undefined method `map’ for nil:NilClass” error.
By mistake, I realized that the sometimes the form posted and sometimes it didn’t. Then I realized that there were Active Record validation errors with the submitted form, but the page wasn’t showing, so I couldn’t see that these errors occurred (even while looking at the logs).
I had to search how to fix this, and eventually found this Stack Overflow question.
The solution by Wes Foster, worked for me to ensure that the collection was getting determined when the new action was rendered (after the record didn’t create).
class MyController < ApplicationController
before_action :set_select_collections, only: [:edit, :update, :new, :create]
private
def set_select_collections
@campaigns = current_user.business.campaigns
end
end
Incidentally, if you’re receiving this error and your form isn’t even loading, it probably means that you didn’t define the collection value in your controller (@campaigns in this example).