error handling, rails 4

1

This error happens when the user does not select the option of the select field. The error up would be handled if it did not have the collect:

NoMethodError in Subdisciplinas#create
Showing _form.html.erb where line #18 raised:

undefined method 'collect' for nil:NilClass

    <%= f.select :disciplina_id, 
        options_for_select(
          @disciplinas.collect { |disciplina| [disciplina.nome.titleize, disciplina.id] }, @subdisciplina.disciplina_id), {prompt: 'Selecionar disciplina'}, { id: 'disciplinas_select' } %>


      </div>

Controller where I believe the error should be handled:

def create
    @subdisciplina = Subdisciplina.new(subdisciplina_params)

    respond_to do |format|
      if @subdisciplina.save
        format.html { redirect_to @subdisciplina, notice: 'Subdisciplina was successfully created.' }
        format.json { render :show, status: :created, location: @subdisciplina }
      else
        format.html { render :new }
        format.json { render json: @subdisciplina.errors, status: :unprocessable_entity }
      end
    end
  end
    
asked by anonymous 26.10.2016 / 05:35

1 answer

1

You are not loading @disciplinas into create . Since it gives some validation error, it tries to render the view again, but @disciplinas is empty.

Load it just like you should have done in action new

    
27.10.2016 / 02:45