ruby-on-railsrubynomethoderror

Rails: undefined method `capitalize' for nil:NilClass


I'm having a store controller like this :

class StoreController < ApplicationController

  helper_method :product_type

  def store
    cat=params[:cat]
    subcat=params[:subcat]
    if cat.empty?
        @store=SubCategory.find_by_name(params[:subcat]).products.where(product_type: params[:type]).paginate(:page => params[:page], :per_page => 12)
        @subcat=params[:subcat]
        @cat=""
    else
        @store=Category.find_by_name(params[:cat]).products.where(product_type: params[:type]).paginate(:page => params[:page], :per_page => 12)
        @cat=params[:cat]
        @subcat=""
    end
    product_type
  end

  def show
    @show=Product.where(product_type: params[:type]).paginate(:page => params[:page], :per_page => 12)
    product_type
  end

  def product
    @product=Product.find(params[:product_id])
    product_type
  end

  def product_type
    @type=params[:type]
  end

end  

In any case, I'm calling the show action first. So, the @type variable gets it's value there itself. So that the @type variable be available in all, methods I have called the product_type method in all other methods.

I'm calling all these variables form a partial dropdown which is a dropdown list and common to the whole site,like a header, like this:-

<%=link_to "T-shirt", store_path(cat:"",subcat:"tshirts",type: @type) %>  

The problem is, I'm able to navigate through this dropdown links in all the methods of StoreController except the product method.Meaning, when I call the links in dropdown list via the store,show pages it works fine but it throws the following error when called via product page.

undefined method `capitalize' for nil:NilClass

The @type contains a string which I'm capitalizing. Where am I doing wrong?

My store.html.erb has this line

<h1><%= @type.capitalize+"'s " + @subcat.capitalize + @cat.capitalize %></h1>  

Solution

  • The error is telling you that you are calling capitalize method on nil.

    I see 2 potentials issues here:

    1. Using find_by_name
    2. What if params[:subcat] is nil or params[:cat] is nil

    Using find_by_name will not raise an exception if no record is found, nil will be returned.

    Your conditions checking if params[:cat] or params[:subcat] are defined are not right. nil value can occur if some params are missing.

    You might want to check:

    if params[:cat].blank?
      # ...
    end
    
    if params[:subcat].blank?
      # ...
    end
    

    I would also use blank? instead of empty? (checking for both nil and "").