1
0

More than 3 years have passed since last update.

undefined method `map' for nil:NilClassエラー

Posted at

20210524-205440.png

map, map! メソッドとは

map は、配列の要素の数だけブロック内の処理を繰り返し、結果として作成された配列を返します。mapは元の値に対して影響を与えないのに対し、map!は元の値を書き換えます。また、Rubyには collectメソッドがありますが、これはmapメソッドの別名です。

【誤】
  def index
    @products = Product.all
  end

  def search
    @results = @p.result.includes(:category)
    set_product_column
  end

  private

  def search_product
    @p = Product.ransack(params[:q])
  end

  def set_product_column
    @product_name = Product.select("name").distinct
  end 
【正】
  def index
    @products = Product.all
    set_product_column
  end

  def search
    @results = @p.result.includes(:category)
  end

  private

  def search_product
    @p = Product.ransack(params[:q])
  end

  def set_product_column
    @product_name = Product.select("name").distinct
  end 

indexにあるべきset_product_columnがsearchアクションにあったため

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0