Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Rails select_tag undefined method `map' for nil:NilClass

I have my problem, kinda solved, but I think its a bit clumsy way, so hope to get a better way, as well as a better understanding whats going on here.

_form.html.erb:

 <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select one!") %>

products_controller.rb:

def new
  @product = Product.new
  @categories = Category.all.map { |c| [ c.name, c.id ] }
end

If user submits form without selecting any of the select_tag options he gets undefined method 'map' for nil:NilClass error.

I know that it comes since my @categories is nil, but I cant figure how to avoid that..?

My final solution, that is working:

<%= select_tag(:category_id, options_for_select(@categories || Category.all.map { |c| [ c.name, c.id ] }), :prompt => "Select one!") %>

But I feel there is a better way. Also I think, that by assigning a default select_tag value with :selected might work as well, but I couldnt implement it with my knowledge of Ruby syntax...

Upvotes: 2

Views: 4089

Answers (3)

Aleksandar
Aleksandar

Reputation: 41

You can try something like this as well.

products_controller.rb:

class ProductsController < ApplicationController
  before_action :set_select_collections, only: [:edit, :update, :new, :create]

  private
    def set_select_collections
      @categories = Category.all.map { |c| [ c.name, c.id ] }
    end
end

After that you should be able to use:

_form.html.erb:

<%= select_tag(:category_id, options_for_select(@categories), include_blank: "Select one!") %>

Upvotes: 0

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

Yes you can go with helper method than using Category.all in every view

def categories
  Category.all.map { |c| [ c.name, c.id ] }
end

and use it in views

<%= select_tag(:category_id,
               options_for_select(categories), 
               include_blank: "Select Category") %>

Upvotes: 0

SnehaT
SnehaT

Reputation: 309

Please try this way of select_tag:

select_tag(:category_id, options_from_collection_for_select(Category.all, :id, :name), include_blank: "Select Category")

Let me know if you face any issue..

Upvotes: 6

Related Questions