当我创建一个列表时,我收到此错误

时间:2016-04-13 17:16:05

标签: ruby-on-rails ruby

nil的未定义方法`map':NilClass

  <% end %>

  <div class="form-group">
    <%= select_tag(:location_id,options_for_select(@locations), :prompt=>"select your location")%>
  </div>

  <div class="form-group">
    <%= select_tag(:category_id,options_for_select(@categories), :prompt=>"select a category")%>

listing_controller.rb

def new
  @listing = Listing.new
  @categories = Category.all.map{|c| [c.name, c.id]}

  @locations= Location.all.map{|c| [c.name, c.id]}
end


def edit
   @categories = Category.all.map{|c| [c.name, c.id]}
    @locations= Location.all.map{|c| [c.name, c.id]}
end


def create
  @listing = Listing.new(listing_params)

  @listing.category_id = params[:category_id]
  @listing.location_id = params[:location_id]

  @listing.user_id = current_user.id


  respond_to do |format|
    if @listing.save
      format.html { redirect_to @listing, notice: 'Listing was successfully created.' }
      format.json { render :show, status: :created, location: @listing }
    else
      format.html { render :new }
      format.json { render json: @listing.errors, status: :unprocessable_entity }
    end
  end
end

2 个答案:

答案 0 :(得分:0)

nil类的未定义方法映射意味着您在某些内容上调用该方法为零。 Nil类没有那种方法。

调试代码以找出导致对象为nil class的原因

答案 1 :(得分:0)

您可以在将值分配给选择选项标记之前删除此错误,如果其值为零,则由以下代码

<div class="form-group">
   <% unless @locations.empty? %>
    <%= select_tag(:location_id,options_for_select(@locations), :prompt=>"select your location")%>
   <% end %>
</div>

<div class="form-group">
  <% unless @categories.empty? %>
    <%= select_tag(:category_id,options_for_select(@categories), :prompt=>"select a category")%>
  <% end %>