【问题标题】:undefined method `map' for nil:NilClass Did you mean? tap - How to fix?nil:NilClass 的未定义方法 `map' 你的意思是?点击 - 如何解决?
【发布时间】:2019-11-19 06:46:35
【问题描述】:

我正在制作一个 Rails 应用程序,它上面会有一些“产品”。产品将有照片、名称、类别、代码和描述。

我尝试了很多方法,但都没有成功。

Products_controller 的 NEW 和 CREATE 方法:

def new
    if !logged_in?
        redirect_to root_path
    end
    if logged_in?
        @product = current_user.products.build
        @categories = Category.all.map{ |c| [c.name, c.id] }
    end
end 
def create
    @product = current_user.products.build(product_params) 
    @product.category_id = params[:category_id]
    if @product.save
        redirect_to root_path
    else 
        render 'new'
    end

HTML 代码:

<div class="col-md-6 col-md-offset-3">
<div class="deniso">

<% <h1>Shto Produkt:</h1>
   <%= simple_form_for @product, :html => {:multipart => true} do |f| %>
<%= f.file_field :product_img %>
 <div class="cate">  
   <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Zgjidhni kategorine:") %>
  </div> 
  <h4>Emri i produktit</h4>
   <%= f.input :title, label: "Emri i Produktit:" %>
   <h4>Kodi</h4>
   <%= f.input :kodi, label: "Kodi:" %>
   <h4>Qmimi<h4>
   <%= f.input :qmimi, label: "Qmimi:" %>
   <h4>Pershkrimi</h4>
   <%= f.input :pershkrimi, label: "Pershkrimi:" %>
   <div class="btn btn-1">
   <%= f.button :submit %>
   </div>
   <% end %>
   </div>

    <%= link_to "Kthehuni mbrapa", root_path, class: "btn-custom2" %>

    </div>
    </div>
    </div>

错误代码:

NoMethodError in Products#create
Showing C:/Users/PC/Desktop/Npshkodra/app/views/products/new.html.erb where line #12 raised:

undefined method `map' for nil:NilClass
Did you mean?  tap
<%= f.file_field :product_img %>
 <div class="cate">  
   <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Zgjidhni kategorine:") %>
  </div> 
  <h4>Emri i produktit</h4>
   <%= f.input :title, label: "Emri i Produktit:" %>

我希望这个产品会被创造出来。

编辑: 我试图在create 方法上声明@categories,但它仍然不起作用:

      @categories = Category.all.map{ |c| [c.name, c.id] }
       @product = current_user.products.build(product_params) 
       @product.category_id = params[:category_id]
       if @product.save
           redirect_to root_path
       else 
           render 'new'
       end
    end 
     ```

【问题讨论】:

  • 错误的完整堆栈跟踪是什么?
  • 问题是@categoriesnil 因为你没有在你的create 方法中定义它。
  • 那要怎么解决呢?
  • “它仍然无法正常工作” ...是否有不同的错误?同样的错误?

标签: ruby-on-rails ruby methods


【解决方案1】:

检查map 方法中的new 调用。 @categories = Category.all.map{ |c| [c.name, c.id] } 这可能是错误的原因。如果没有找到记录,'AсtiveRecord' 返回一个空数组,但无论如何我都会验证输出,以防发生意外情况。

【讨论】:

    【解决方案2】:

    您似乎从 AR 查询中收到 nil。要处理此类错误,您可以尝试以下操作:

    @categories = Category.all.to_a.map{ |c| [c.name, c.id]}
    

    但结果将是 0,因为没有任何结果。

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2022-06-13
      相关资源
      最近更新 更多