0

I've got a working form that properly saves all attributes including a collection_select. However, when I add validates :title, presence: true and try to submit, I get

undefined method 'map' for nil:NilClass

My new action:

class ItemsController < ApplicationController
  def new
    @item = Item.new
    @categories = Question.editable_by(current_user)
    respond_to do |format|
      format.html { render :layout => true}
      format.json { render :json => @item  }
      format.js
    end

  end
end

View is items\_form.html.haml

Does not work

= f.collection_select :question_id, @categories, :_id, :iqs_item

Works

= f.collection_select :question_id, Question.editable_by(current_user), :_id, :iqs_item

This works when I add the @categories object from the controller to the view. I'm guessing something doesn't get passed for the error function in the view or it can't map the select when it tries to redraw the page with errors??

Please assist. Again, I can get it to work, but I'd rather not be putting method calls in the view.

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155
  • Can you share the error stacktrace – Kirti Thorat Feb 28 '14 at 17:53
  • I am guessing that `Question.editable_by(current_user)` is returning nil i.e., for current_user there are no editable questions. – Kirti Thorat Feb 28 '14 at 17:54
  • @KirtiThorat, best way to do that is from the `development.log`? And, no, `Question.editable_by(current_user)` consider to be `Question.all`. That function works fine in both controller and view. It's only after submit that it is causing errors. – Kevin Brown Feb 28 '14 at 17:58
  • Problem is not with function, but with what its returning. Print the value of @categories either in the `controller` or in the `view`. Check if its nil or something else – Kirti Thorat Feb 28 '14 at 18:06
  • Yes you can get it from log file. You could also copy the error trace from the console, where you are running the server. – Kirti Thorat Feb 28 '14 at 18:16

1 Answers1

1

= f.collection_select :question_id, @categories, :_id, :iqs_item

line would give undefined method 'map' for nil:NilClass error when collection given to it ,i.e., @categories is set as nil.

Add below mentioned code in the view, if your page displays successfully(without error message) and without a select then you know that @categories was set as nil.

- unless @categories.nil?
    = f.collection_select :question_id, @categories, :_id, :iqs_item

EDIT

Also set @categories in the create method

Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108