ruby-on-railsform-for

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...


Solution

  • 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..