【问题标题】:Undefined method `call' for nil:NilClassnil:NilClass 的未定义方法“调用”
【发布时间】:2012-02-17 06:23:42
【问题描述】:

所以我在玩 Ryan Bates Simple_Form railscast,当我尝试提交表单时出现以下错误:

NoMethodError in Products#index

Showing /home/panos/sites/store/app/views/products/index.html.erb where line #8 raised:

undefined method `name' for nil:NilClass
Extracted source (around line #8):

5:     <h2><%= link_to product.name, product %></h2>
6:     <div>
7:       Price: <%= number_to_currency product.price %><br />
8:       Category: <%= product.category.name %><br />
9:       <%= link_to "Edit", [:edit, product] %>
10:     </div>
11:   <% end %>
Rails.root: /home/panos/sites/store

Application Trace | Framework Trace | Full Trace
app/views/products/index.html.erb:8:in `block in _app_views_products_index_html_erb___762171406_75615480_549568821'
app/views/products/index.html.erb:4:in `each'
app/views/products/index.html.erb:4:in `_app_views_products_index_html_erb___762171406_75615480_549568821'

这是我的 index.html.erb 文件:

<% title "Products" %>

<div class="product">
  <% for product in @products %>
    <h2><%= link_to product.name, product %></h2>
    <div>
      Price: <%= number_to_currency product.price %><br />
      Category: <%= product.category.name %><br />
      <%= link_to "Edit", [:edit, product] %>
    </div>
  <% end %>
</div>

<p><%= link_to "New Product", new_product_path %></p>

这是我的 form.html.erb 文件:

<%= simple_form_for @product do |f| %>
  <%= f.error_messages %>
  <table border="1">
  <tr>
  <td><%= f.input :name %></td>
  <td><%= f.input :price, :hint => "prices should be in USD" %></td>
  <td><%= f.input :released_on %></td>
  <td>  <%= f.association :category, :include_blank => false %></td>
  <td><%= f.input :rating, :collection => 1..5, :as => :radio %></td>
  <td><%= f.input :discontinued %></td>
  <td><%= f.button :submit %></td>
  </tr>

<% end %>

我知道错误是因为 Category 字段为空(nill)而产生的,但我不知道如何修复它,以便即使使用 nill 值也可以显示。

有人可以帮忙吗?

【问题讨论】:

    标签: ruby-on-rails undefined railscasts


    【解决方案1】:

    或者更简洁一点。

    Category: &lt;%= product.category.name if product.category %&gt;

    Category: &lt;%= product.category.try(:name) %&gt;

    虽然try 方法被很多人所反对。

    【讨论】:

      【解决方案2】:

      试试这个:

      Category: <%= product.category.name unless product.category.nil? %>
      

      【讨论】:

        【解决方案3】:

        似乎至少有一行 product.category 的值为 nil,因此当 product.category 被取消引用以访问“名称”时会出现异常。

        在撰写本文时提供的答案中,“除非”解决方案防止引用 nil。 'try' 解决方案在异常发生的情况下安全地捕获异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-27
          • 2013-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多